从多个异步函数(promises)收集数据

时间:2015-04-04 11:34:58

标签: javascript node.js asynchronous promise

鉴于您必须从多个异步函数或承诺中获取数据的情况,收集和保留数据的最佳方法是什么,以便在完成后可以使用它。一个示例情况是需要在单个页面中呈现的多个数据库查询。

我遇到了下面的代码,对我来说看起来像一个固体模式,但对异步游戏不熟悉是不确定的。

function complexQuery(objectId) {
    var results = {};
    return firstQuery.get(objectId).then(function (result1) {
            results.result1 = result1;
            return secondQuery.find();
        })
        .then(function (result2) {
            results.result2 = result2;
            return thirdQuery.find();
        })
        .then(function (result3) {
            results.result3 = result3;
            return results;
        });
}

complexQuery(objectId)
    .then(function (results) {
        //can use results.result1, results.result2, results.result3
        res.render('dash', results); //example use
    });

处理这种情况的最佳方法是什么?

编辑以供澄清:必须是连续的,查询可能需要来自先前承诺结果的信息。

2 个答案:

答案 0 :(得分:2)

最简单的方法是使用Promise.all,它可以并行执行查询:

function complexQuery(objectId) {
    return Promise.all([firstQuery.get(objectId),
                        secondQuery.find(),
                        thirdQuery.find()])
    .then(([result1, result2, result3] => {result1, result2, result3}); // ES6 syntax
    /* ES5 equivalent would be
    .then(function(results) {
        return {result1: results[0], result2: results[1], result3: results[2]};
    }); */
}

如果您需要按顺序执行查询(因为它们彼此依赖),请查看How do I access previous promise results in a .then() chain?其中不同的策略(例如您的问题中给出的策略,imo is not a good one)深入解释。

答案 1 :(得分:0)

最好的方法是将所有的promises存储在一个数组中并使用Q.all()或异步等效项,我认为在完成所有操作后运行函数是相同的

相关问题