async function main() {
console.log("Start")
await Author.create({name: 'Some Guy'}, function (err, awesome_instance) {
console.log("This should be next, but its not")
});
console.log("This should be last, but it's not")
}
main()
最终的日志语句在第二个之前记录。如果我使用await
?
答案 0 :(得分:2)
当指定回调时,Mongoose方法切换到回调模式,当没有指定回调时切换到promise模式。
应该是:
async function main() {
try {
await Author.create({name: 'Some Guy'});
} catch (err) {
console.error(err);
}
console.log("This should be next, but its not");
console.log("This should be last, but it's not");
}
答案 1 :(得分:0)
您的await
正在等待Author.create
返回/解决。但是第一个日志语句在回调中,由Author.create
异步调用,因此await
不适用。
如果您使用promises实施Author.create
,则可以使用await
。