如何在Model.find(obj,callback)上传播回调承诺值?

时间:2015-11-27 18:28:10

标签: javascript mongodb callback mongoose promise

好的,我正在努力解决这个问题。过去一周我花了很多时间试图找出如何使这项工作。我已经学会promises并做了一些很酷的东西 - 我很喜欢它。但是,我无法做到这一点。

我正在使用Mongoose Model.find()方法。此方法接收两个参数:将用于查询的object和将接收callback个对象的(error, data)函数。我正在呼叫.find并传递findUser功能。

UserModel.find(userObj, findUser)
            .then(userFound, createUser);

findUser内,我正在创建Promise并解析或拒绝它。

var findUser = function(err, data) {
    var p1 = new Promise( function (resolve, reject) {
        if (data.length) {
            console.log('Resolved on findUser');
            resolve();
        } else {
            console.log('Rejected on findUser');
            reject();
        }
    });
};

但是,无论findUser发生什么,总是会调用成功回调。在控制台上,我可以看到类似这样的内容:

Rejected on findUser
Resolved on find
var userFound = function () {
    console.log('Resolved on find');
};

var createUser = function () {
    console.log('Rejected on find');
}

我如何将承诺值从findUser传播到.find

1 个答案:

答案 0 :(得分:3)

你可以尝试这样的事情。代码中的所有更改都会被注释。

// Remove err argument
var findUser = function(data) {
    // Instead of creating a new Promise, 
    // we return a value to resolve
    // or throw a value to reject.
    if (data.length) {
        console.log('Resolved on findUser');
        // Resolve this Promise with data.
        return data;
    } else {
        var reason = 'Rejected on findUser';
        console.log(reason);
        // Reject this Promise with reason.
        throw reason;
    }
};

// Function gets data passed to it.
var userFound = function(data) {
    console.log('Resolved on find');
};

// Function gets reason passed to it.
var createUser = function(reason) {
    console.log('Rejected on find');
};

// Promises will chain and propagate errors as necessary.
UserModel.find(userObj)
.then(findUser)
.then(userFound)
.catch(createUser);