javascript Bluebird 承诺 - 如何分解数组,然后映射它?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23986382/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Bluebird promises - how to explode an array, then map it?
提问by Alastair
If I have an array:
如果我有一个数组:
['one.html','two.html','three.html']
how could I explode that array, apply a chain of promises to it, then combine it back together again? At the moment my code is like this:
我怎么能分解那个数组,对它应用一系列承诺,然后再把它组合在一起?目前我的代码是这样的:
Promise.map(['one','two','three'], function(i) {
dbQuery('SELECT ' + i);
}).then(function(results) {
// This has an array of DB query results
});
I'm imagining something like:
我在想象这样的事情:
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
});
Now, I know Bluebird doesn't have these functions, so I'm wondering what the correct Promise-y way is of doing this?
现在,我知道 Bluebird 没有这些功能,所以我想知道这样做的正确 Promise-y 方法是什么?
回答by Esailija
You can use a chain of maps:
您可以使用一系列地图:
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
});
However the above will not be as concurrent as
然而,以上不会像
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
});
回答by aarosil
Bluebird does in fact have this. but it doesn't modify the array: Promise.each()
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
});
Chaining maps or adding more promises off dbQuery works well, but each()
could be advantage if you only want a side effect when touching individual results
从 dbQuery 链接映射或添加更多承诺效果很好,但each()
如果您只想要在接触单个结果时产生副作用,则可能是有利的