javascript - 我怎样才能让底部的 console.log 等到它全部完成,然后告诉我答案而不是等待?

标签 javascript node.js asynchronous async-await

这是我的代码,我知道有人在这里解释 await 函数,但我似乎无法理解为什么我的代码不起作用,在函数内部它完美地 console.logs 数据库,也在 .然后是一段代码,但是当涉及到外面的console.log时就不行了。

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);})

它不会显示在 console.log(result) 中。

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

要在这一行下显示,我做错了什么?

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

console.log 上的结果

Promise { <pending> } ' why is it still pending?'

最佳答案

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

console.log(await asyncCall())

关于javascript - 我怎样才能让底部的 console.log 等到它全部完成,然后告诉我答案而不是等待?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48744446/

相关文章:

javascript - 播放音频文件返回 "Uncaught (in promise)"但在控制台中有效

javascript - Highcharts map 的最大宽度或最大高度

javascript - 使用 DataTables 在服务器端模式下具有单独搜索输入的多个表

javascript - 如何从异步调用返回响应?

node.js - 将 unsigned char 缓冲区与 node-ffi 一起使用

javascript - 无需使用 Node.js 设置本地服务器?

javascript - 跳到主回调,并在异步 waterfall Node js 中产生结果

javascript - 将聚集的 obj 转换为数组

javascript - Parent() div 的 UL

node.js - Sequelize 魔法关联方法的警告