具有多个返回值的嵌套promise

时间:2015-01-29 18:00:35

标签: javascript node.js asynchronous promise bluebird

我正试图从Async.waterfall切换到Bluebird承诺(性能原因,也因为我认为承诺更优雅,但这是另一个讨论)。

我在Async.waterfall中有以下代码:

async.waterfall([
    function callGoogle(next) {
        request.get(config.google.meEndpoint, {
            auth: {bearer: req.body.access_token},
            json: true
        }, next);
    },
    function handleGoogleResponse(response, body, next) {
        //error handling

        next(null, body);
    },
    function queryDatabase(googleUserInfo, next) {
        googleUserModel
            //.findOne(...), etc.
            .exec(function (err, usr) {
                next(err, usr, googleUserInfo);
            });
    },
    function handleUser(googleUser, googleUserInfo, next) {
        //googleUser is my internal representation of a user logged in using Google
        //googleUserInfo is the information provided by Google
        //If googleUser exists, I'm done, otherwise I can use googleUserInfo to create a new googleUser
    }], function done());

我面临的问题是使用承诺,我得到这样的东西:

httpGet(config.google.meEndpoint, {
    auth: {bearer: req.body.access_token},
    json: true
}).spread(function handleGoogleResponse(response, body){
    //error handling

    return body;
}).then(function queryDatabase(googleUserInfo){
    return googleUserModel
        //.findOne(...), etc.
        .execAsync();
}).then(function handleUser(googleUser){
    //I don't have access to the previous then's googleUserInfo!
});

我的queryDatabase函数有一个嵌套的promise(execAsync),因此下一个then只会获得mongoose返回的googleUserModel。

如何将参数级联到承诺链中?

0 个答案:

没有答案