首页 > 解决方案 > 为什么异步函数返回 Promise控制台中的错误

问题描述

我想使用 async 函数将特定值从我的数据库中提取到我的全局函数中,以便我可以在应用程序的其他部分使用它。

async function dimension() {
  const result = await Settings.find({_id : "5d7f77d620cf10054ded50bb"},{dimension:1}, (err, res) => {
    if(err) throw new Error(err.message, null);
     const holder = res[0].dimension; 
    return holder;
    console.log(holder) /// this print the expected result, that i want to make global

  });
  return {
    result
  }; 
};



console.log(dimension())

但是维度()的console.log给了我这个

Promise { <pending> }

而不是相同的值

console.log(holder)

什么都没有给我。

标签: node.js

解决方案


问题是你一调用就打印结果dimension(),但由于这个函数是async,它返回一个尚未解决的承诺。

您不需要在此处使用async/ awaitSettings.find()似乎返回一个Promise. 一旦承诺得到解决,您就可以直接返回它Promise并使用.then()它来做某事。

像这样 :

function dimension () {
  return Settings.find({ _id: '5d7f77d620cf10054ded50bb' }, { dimension: 1 }, (err, res) => {
    if (err) {
      throw new Error(err.message, null);
    }
    return res[0].dimension;
  });
}

dimension().then(result => {
  //print the result of dimension()
  console.log(result);
  //if result is a number and you want to add it to other numbers
  var newResult = result + 25 + 45
// the variable "newResult" is now equal to your result + 45 + 25
});

有关 Promises 和 async/await 的更多信息


推荐阅读