首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Bluebird .then():不能正常工作

Bluebird .then():不能正常工作
EN

Stack Overflow用户
提问于 2016-01-21 22:45:13
回答 1查看 201关注 0票数 0

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

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

然后,我看到函数被再次执行,并且.then()被成功执行。另外,我还可以在控制台中打印出正确的信息。

为什么会发生这种情况?我实现promises的全部原因是因为我想等待执行then()-action,因为必须首先检索我的数据。但是代码仍然过早地跳到了.then()操作。

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

下面是我的代码:

代码语言:javascript
复制
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);
        });
};
EN

回答 1

Stack Overflow用户

发布于 2016-01-21 23:39:14

当使用原生npm模块时,您应该在这里使用回调,就像在documentation中一样。因此,对于您的示例,这意味着:

代码语言:javascript
复制
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;
        });
};

如果你想使用promises,那么也许你应该考虑使用像mongoose这样的东西。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34926796

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档