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

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

user7890
1#
user7890 Published in September 21, 2018, 8:03 am

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?'
share|improve this question
  • 2
    await returns a promise, it does not wait for a value to return. You should still call .then() or make the call await in the console.log function when asking for the value. – Randy Feb 12 at 10:43
  • Problem is that Im then wanting to send these values over to the client side of my game, socket.emit('allScores', asyncCall()); – Andrew Feb 12 at 10:46
  • 2
    @Andrew Well, you can't. An async call always returns a promise, there's no way to trick time. await does not cause the function to synchronously return a future value. You have to use asyncCall().then(e => socket.emit('allScores', e)) or socket.emit('allScores', await asyncCall()). – Bergi Feb 12 at 10:54

3 Answers 3

active oldest votes
up vote 2 down vote
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.340444 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO