为什么异步函数在控制台中返回承诺<pending>错误



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

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())

但是维度((的控制台.log给了我这个

Promise { <pending> }

而不是相同的值

console.log(holder)

什么都不给我。

问题是你一调用它就会打印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
});

有关承诺和异步/等待的更多信息

你必须等待你的结果,像这样:

const result = await dimension();
console.log(result);

在这种情况下,您甚至不需要使原始函数异步,只需这样编写:

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

async function myGlobalFunc() {
const result = await dimension();
console.log(result);
}

使其全局可用的最佳方法是将function dimension放在某个文件中。然后,在需要值的地方,只需需要它并等待其值。例如

// get-dimension.js 
// ...const Settings = require... comes here
module.exports = function getDimension() {
return Settings.find({_id : "5d7f77d620cf10054ded50bb"},{dimension:1}, (err, res) => {
if(err) throw new Error(err.message, null);
const holder = res[0].dimension; 
return holder;
});
}
// your other modules, e.g.
// my-service-handler.js
const getDimesion = require('./get-dimension');
async function myServiceHandler() {
const dimension = await getDimension();
// do stuff with dimension.
}

您正在使用async/await,但您将其与回调混合在一起,这是不可取的,因为它会导致混淆。目前尚不清楚您希望在回调中发生什么,但return holder;可能不会执行您希望它执行的操作,但从回调返回的工作方式与从 promise 处理程序返回的工作方式不同。您的整个实现应该使用承诺,以便async/await语法更自然地读取(如预期的那样(。

async function dimension() {
// We're already awaiting the result, no need for a callback...
// If an error is thrown from Settings.find it is propagated to the caller, 
// no need to catch and rethrow the error...
const res = await Settings.find({_id: "5d7f77d620cf10054ded50bb"}, {dimension: 1});
return {result: res[0].dimension};
}
(async () => {
try {
console.log(await dimension());
} catch (err) {
console.error(err);
}
})();

在你的代码中使用dimension((.then((,那么它将正常工作。

async function globalDimension() {
const data = await Users.findOne({ phone: 8109522305 }).exec();
return data.name;
}
globalDimension().then(data => {
console.log(data);
});

相关内容

最新更新