O
O
Oleg Frolov2020-04-27 17:39:27
Node.js
Oleg Frolov, 2020-04-27 17:39:27

Again async/await, how to synchronously get the result of a query into a variable?

Please, help!
I can not overcome the asynchronous request to the nedb database.
How to get a list of entries into the res variable?

const Datastore = require('nedb-promises')
let datastore = Datastore.create('./database/test.db')

var res = (async () => {
await datastore
      .find({})
      .then(function(docs){
          console.log(docs) // здесь возвращает списк
          return docs
      })
})()
console.log(res) // здесь вместо списка Promise { <pending> }

Answer the question

In order to leave comments, you need to log in

6 answer(s)
L
Lynn "Coffee Man", 2020-04-27
@Lynn

No way.
Not at all.
No, that won't work either.

M
McBernar, 2020-04-27
@McBernar

The last console.log will not wait for your async. Why should he do this?
But everything that is written inside async will wait for await.

L
Leo, 2020-04-29
@DLeo13

Friend, you made a promise without a return. Put a return on an arrow function. Now the function does not return anything. But globally, the code section is so-so.
PS Inside then also does not have a return. Write return Promise.resolve(data) if you still need the console

S
Sn0oSm0oMrIK, 2020-04-29
@Sn0oSm0oMrIK

In your example with python, the value is also displayed in async. Why does this not suit the node?

P
p1kaso, 2020-04-29
@p1kaso

To work synchronously with asynchronous requests, use Promise.all, it should help in your case.

const Datastore = require('nedb-promises')
let datastore = Datastore.create('./database/test.db')

Promise.all([datastore.find({})]).then(res=>console.log(res))

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question