A
A
Alexander Koshelev2018-09-14 20:31:43
Node.js
Alexander Koshelev, 2018-09-14 20:31:43

How to get the result of a promise when querying the database?

Good evening everyone. I’ll say that I read an article about promises on Habré, but I didn’t understand how, using my example, I can get the result of a promise, namely users from the database. The Habr article says that inside the then function, you can do the following 3 things
1. Return (return) another promise
2. Return (return) a synchronous value (or undefined)
3. Throw (throw) a synchronous error
And here is my code example:

router.get('/index', (req, res) => {
  let getProfile = User.findAll({    <---- findAll - Метод sequelize а диалект у меня postgress
    offset: 0, limit: 1
  }).then(result => {
    return result
  })
  .catch(console.log.bind(console));
  console.log(getProfile);  <------- получаю Promise результат которого мне нужен (данные из БД)
  res.render('index', {data: getProfile});  <------ пробую вывести на клиенте данные из БД с помощью .ejs
});

This is what console.log(getProfile);
Promise {
  _bitField: 0,
  _fulfillmentHandler0: undefined,

  _rejectionHandler0: undefined,
  _promise0: undefined,
  _receiver0: undefined }

Please tell me how to be in this situation?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2018-09-14
@Xandr24

Read about async/await, you will have something like:

async (req, res) => {
  let getProfile = await User.findAll

Well, or in then pull res.render.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question