【问题标题】:Bluebird .then(): not working as it shouldBluebird .then():不能正常工作
【发布时间】:2016-01-24 12:14:25
【问题描述】:

我刚开始使用 Promise 和 Bluebird。在调试时,我可以看到我的函数执行了两次:

首先我得到这个错误:TypeError: Uncaught error: Cannot read property 'then' of undefined

然后我看到函数又执行了,.then()执行成功了。我也得到了在控制台中打印的正确信息。

为什么会这样?我实现承诺的全部原因是因为我想等待执行then()-action,因为必须先检索我的数据。但是代码仍然过早地跳转到 .then() 动作。

为什么会发生这种情况,我该如何预防?

这是我的代码:

exports.findUser = function(userId){

    var ObjectID = require('mongodb').ObjectID;
    var u_id = new ObjectID(userId);

    db.collection('users')
        .findOne({'_id': u_id})
        .then(function(docs) { //executed twice, first time error, second time success
            console.log(docs); //prints correct info once executed
            return docs;
        })
        .catch(function(err) {
            console.log(err);
        });
};

【问题讨论】:

  • 如果你答应了,你的意思是写findOneAsync
  • TypeError: Uncaught error: db.collection(...).findOneAsync is not a function
  • Promise.promisifyAll(require("mongoose"))了吗?
  • 我应该把那行放在哪里?
  • var mongoose = Promise.promisifyAll(require("mongoose"))

标签: javascript node.js mongodb promise bluebird


【解决方案1】:

使用本机 npm 模块时,您应该在此处使用回调,例如 documentation。因此,对于您的示例,这意味着:

exports.findUser = function(userId){

    var ObjectID = require('mongodb').ObjectID;
    var u_id = new ObjectID(userId);

    db.collection('users')
        .findOne({'_id': u_id}, function(err, docs){
            console.log(docs); //prints correct info once executed
            return docs;
        });
};

如果你想使用 Promise,也许你应该考虑使用类似 mongoose 的东西。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-30
    • 2010-11-30
    • 2021-10-02
    • 2017-08-06
    相关资源
    最近更新 更多