Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make the console.log at the bottom wait until its all complete, then show me the answer instead of waiting?

This is the code I have, I know there has been people to explaining the await functions here but I can not seem to understand why mine is not working, inside the function it console.logs the database perfectly, also on the .then section of code, but when it comes to the console.log outside it won't work.

function resolveAfter1() {
  return new Promise((resolve, reject) => {
    var scoresFromDb = db.account.find({}, { username: 1, score: 1 }).toArray(function(err, result) {
          if (err) 
              reject(err);
          else
              resolve(result);
              // console.log(result);
    });
  });
}

resolveAfter1() // resolve function
    .then((result)=>{console.log(result);})
    .catch((error)=>{console.log(error);})

It won't show on the console.log(result) under either.

 async function asyncCall() {
      var result = await resolveAfter1();
      return result
      // console.log(result);
    }

To display it under this line, what Im I doing wrong?

console.log(asyncCall(), ' why is it still pending?');

result on the console.log

Promise { <pending> } ' why is it still pending?'
like image 621
Andrew Avatar asked Jan 27 '26 06:01

Andrew


1 Answers

asyncCall is an async function, you have to await for it to resolve.

console.log(await asyncCall())

like image 122
Akash Avatar answered Jan 29 '26 20:01

Akash