首页 文章

Bluebird承诺 - 如何爆炸数组,然后映射它?

提问于
浏览
7

如果我有一个数组:

['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方式是做什么的?

2 回答

  • 8

    您可以使用一系列 Map :

    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
    });
    
  • 15

    蓝鸟确实有这个 . 但它不会修改数组: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上添加更多promise可以很好地工作,但如果你只想在触摸单个结果时需要副作用,那么_2480555可能会有优势

相关问题