在我的异步函数中,我无法获得真正的优先级输出。
预期结果首先是{control : 1}
,然后是{control : 2}
。
但结果却恰恰相反。
我怎样才能实现它?
NodeJS 代码
edit_settings = async function (params) {
await User.updateOne({ _id: params.id }, query, (error, update_result) => {
console.log({ control : 1 });
if (error) return { success: false, error: { code: 1001 } };
else return { success: update_result.nModified };
});
return await { control : 2 };
}
NodeJS 结果
{ control : 2 }
{ control : 1 }
最佳答案
它看起来不像User.updateOne
返回一个 promise (可能是错误的,但我猜它没有),它接受回调,所以await
-ing 不会执行任何操作。
编辑:解决这个问题的一种方法是创建一个像这样的 promise :
edit_settings = async function (params) {
let res; // the `resolve` method of a promise
const p = new Promise(r => res = r);
User.updateOne({ _id: params.id }, query, (error, update_result) => {
console.log({ control : 1 });
res(); // resolve the promise
if (error) return { success: false, error: { code: 1001 } };
else return { success: update_result.nModified };
});
await p;
return { control: 2 };
}
编辑:根据您的评论,User.updateOne
实际上确实返回了一个 promise ,那么您应该像这样使用它:
edit_settings = async function (params) {
await User.updateOne({ _id: params.id }, query);
console.log({control:1});
return { control : 2 };
}
从您显示的代码来看,您实际上没有对从 promise 返回的值执行任何操作,因此我将其从代码中删除了。
关于javascript - 如何在 NodeJs 中进行异步,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55718438/