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

Ala*_*air 7 javascript promise bluebird

如果我有一个数组:

['one.html','two.html','three.html']
Run Code Online (Sandbox Code Playgroud)

我怎么能爆炸那个数组,对它应用一连串的承诺,然后再把它重新组合起来?目前我的代码是这样的:

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

我想象的是:

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
});
Run Code Online (Sandbox Code Playgroud)

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

Esa*_*ija 15

您可以使用一系列地图:

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
});
Run Code Online (Sandbox Code Playgroud)

但是,上述内容不会同时发生

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
});
Run Code Online (Sandbox Code Playgroud)


aar*_*sil 8

蓝鸟确实有这个.但它不会修改数组: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
});
Run Code Online (Sandbox Code Playgroud)

链接映射或在dbQuery中添加更多promise可以很好地工作,但each()如果您在触摸单个结果时只需要副作用,则可能会有优势