如果我有一个数组:
['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
});
现在,我知道蓝鸟没有这些功能,所以我想知道正确的Promise-y方式是做什么的?
答案 0 :(得分: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
});
答案 1 :(得分: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()
可能会有优势