【问题标题】:Bluebird promises - how to explode an array, then map it?Bluebird 承诺 - 如何爆炸数组,然后映射它?
【发布时间】:2014-06-02 01:56:44
【问题描述】:

如果我有一个数组:

['one.html','two.html','three.html']

我如何分解该数组,对其应用一系列承诺,然后将其重新组合在一起?目前我的代码是这样的:

Promise.map(['one','two','three'], function(i) {
    dbQuery('SELECT ' + i);
}).then(function(results) {
    // This has an array of DB query results
});

我在想象这样的事情:

Promise.map(['one','two','three'], function(i) {
    dbQuery('SELECT ' + i);
})
.explode()
.then(function(result) {
    // Individual result
})
.combine()
.then(function(results) {
    // Now they're back as an array
});

现在,我知道 Bluebird 没有这些功能,所以我想知道正确的 Promise-y 方法是什么?

【问题讨论】:

    标签: javascript promise bluebird


    【解决方案1】:

    您可以使用一系列地图:

    Promise.map(['one','two','three'], function(i) {
        return dbQuery('SELECT ' + i);
    }).map(function(result) {
        // Individual result
    }).map(function(result) {
        // Individual result
    }).map(function(result) {
        // Individual result
    }).then(function(results) {
        // Now they're back as an array
    });
    

    但是上面的不会像并发

    Promise.map(['one','two','three'], function(i) {
        return dbQuery('SELECT ' + i).then(function(result) {
            // Individual result
        }).then(function(result) {
            // Individual result
        }).then(function(result) {
            // Individual result
        })
    }).then(function(results) {
        // Now they're back as an array
    });
    

    【讨论】:

    • @BenjaminGruenbaum :> 后者的缩进不断增加,所以这不是问题
    • 谢谢 - 我认为第二个对我来说最有意义。但很高兴知道我没有发疯!
    • 暂时忘记承诺,“不如并发”本身就是一个迷人的概念。
    【解决方案2】:

    Bluebird 实际上确实有这个。但它不会修改数组:Promise.each()

    var transformed = []
    
    Promise.map(['one','two','three'], function(i) {
        return dbQuery('SELECT ' + i);
    })
    .each(function(result) {
        // This is repeating access for each result
        transformed.push(transformResults(result));
    })
    .then(function(results) {
        // here 'results' is unmodified results from the dbQuery
        // array doesn't get updated by 'each' function
        // here 'transformed' will contain what you did to each above
        return transformed
    });
    

    在 dbQuery 之外链接映射或添加更多承诺效果很好,但如果您只希望在触摸单个结果时产生副作用,each() 可能是优势

    【讨论】:

    猜你喜欢
    • 2021-05-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-27
    • 1970-01-01
    • 2016-09-18
    • 1970-01-01
    • 2019-11-06
    相关资源
    最近更新 更多