node.js - 为什么异步函数返回 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)
什么都没有给我。
解决方案
问题是你一调用就打印结果dimension()
,但由于这个函数是async
,它返回一个尚未解决的承诺。
您不需要在此处使用async
/ await
。Settings.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
});
推荐阅读
- reactjs - 如何使用 service-worker 将文件从 AWS 预缓存到我的 React 应用程序?
- c - C中的多个错误
- ios - Expo 应用程序 iOS 分发证书已过期 - 我如何分配一个新的?
- c# - .NET Core 3.0“找不到 System.String 构造函数错误”尝试从 propertyGrid 修改字符串 []
- javascript - 如何限制 DetailsList 中的最大项目行数?
- python - python中大数据分配的内存异常
- python - Keras 自定义层每次接收相同的输入形状
- php - nginx:php-fpm 正在进入主网站,但不是第二个网站
- java - 如何从使用 TOAD 在 Orcale DB 中编译的 Java 中查看 System.out.println?
- flutter - 在bottomNavigationBar颤动中为文本添加渐变