猫鼬等待不起作用

时间:2018-02-13 19:00:54

标签: javascript mongoose ecmascript-6 async-await

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

,为什么会这样呢?

2 个答案:

答案 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