【问题标题】:Waiting for MongoDB query result等待 MongoDB 查询结果
【发布时间】:2019-04-02 03:22:39
【问题描述】:

我一直在搜索较旧的答案,但不知道如何为我的特定用例设置它,而且许多答案似乎已经过时了。

Node.js 控制台警告说 Promise 库已被弃用,所以我尝试使用 Bluebird(无济于事)。如果有其他解决方案,我可以解决,不必是蓝鸟。

这是我的代码:

let shortInt;
count().then(result => shortInt = result).catch(err => console.log(err));
console.log("shortInt " + shortInt);
//doing some other stuff here

还有我需要等待结果的函数:

async function count() {
   let answer;
   await Url.findOne({}).sort({short_url:-1}).exec(function (err,ur) { if (err) return err; answer = ur.short_url });
   console.log("answer " + answer);
   return answer;
}

对于console.log(shortInt) 我得到'undefined',并且console.log(answer) 总是在最后打印出来,毕竟//做其他事情。

我需要更改什么以便在我继续//做其他事情之前设置 shortInt。

我设置了 mongoose.Promise = require("bluebird");不会收到弃用的警告。

【问题讨论】:

  • 您将同步与异步混合在一起,并将承诺与回调混合在一起。我建议看一些关于 Promise 的教程。我还没有通读这一篇,但谷歌搜索结果最高:guru99.com/node-js-promise-generator-event.html
  • 把剩下的代码放到.then()回调中

标签: node.js mongodb promise mongodb-query bluebird


【解决方案1】:

您的脚本实际上在count() 结果返回之前继续运行,Node 在异步操作之前执行主线程。

您可以将代码移动到解决承诺的范围内。

count()
  .then(shortInt => {
    // we can access shortInt here
    // rest of code ...
  })
  .catch(err => console.log(err));

【讨论】:

    猜你喜欢
    • 2017-10-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-25
    • 2015-10-24
    • 2019-04-19
    • 2022-01-19
    相关资源
    最近更新 更多