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 方法是什么?

4

2 回答 2

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

但是,上述内容不会像

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
});
于 2014-06-02T08:04:49.327 回答
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
});

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

于 2014-07-07T23:16:04.993 回答