【问题标题】:Mongoose await not working [duplicate]猫鼬等待不工作[重复]
【发布时间】:2018-07-24 05:39:58
【问题描述】:
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,为什么会出现这种情况?

【问题讨论】:

  • 你需要返回一个promise,一旦promise被解决,你就可以使用.then

标签: javascript mongoose ecmascript-6 async-await


【解决方案1】:

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");
}

【讨论】:

    【解决方案2】:

    您的await 正在等待Author.create 返回/解决。但是第一条日志语句在回调中,被Author.create异步调用,所以await不适用。

    如果您使用 Promise 实现 Author.create,则可以使用 await

    【讨论】:

    • 如何用 promise 实现?
    • 你可以使用像 mpromise npmjs.com/package/mpromise这样的库
    • 似乎只使用 .then() 就可以了?猜测 cus then() 返回一个承诺
    • 太棒了,您使用的库可能同时支持回调和承诺
    猜你喜欢
    • 2019-05-10
    • 1970-01-01
    • 2018-08-30
    • 2019-03-20
    • 2022-12-18
    • 2019-12-12
    • 2018-07-22
    • 1970-01-01
    • 2018-11-29
    相关资源
    最近更新 更多