【发布时间】:2021-08-06 02:14:52
【问题描述】:
我在异步函数中有以下 sn-p 代码 -
await application.save((err) => {
console.log("hello");
if (err) {
res.status(500).send({ message: "Error encountered" });
}
});
console.log("hey");
为什么“嘿”比“你好”更早打印出来?以及如何修复它以使行为符合预期(等待异步保存操作,只有当它完成并打印“hello”时,才应该打印“hey”)。
以下代码确实将对象保存到 MongoDB,但是当我使用 application.save().then(() => {}) 时,我收到错误“无法读取未定义的属性 'then'”
【问题讨论】:
-
application.save 的函数签名是什么样的?
-
如果你正在使用 await 则无需传递回调将其包裹在 try 和 catch 块中
-
If the value of the expression following the await operator is not a Promise, it's converted to a resolved Promise. 所以,
application.save没有返回 Promise。 -
一般来说 - 一个接受回调的异步函数不会返回 Promise - 有一些智能库有一个接受回调的函数,如果你使用它,它不会返回任何有用的信息,或者将如果您不提供回调,则返回 Promise
-
是您将回调与 async/await 混合的地方,您需要同时解决或仅解决承诺,例如 playcode.io/797474
标签: javascript node.js express mongoose