[英]Node JS Promise.all and forEach
我有一个类似数组的结构,它公开了异步方法。 异步方法调用返回数组结构,这些结构又会公开更多异步方法。 我正在创建另一个 JSON 对象来存储从这个结构获得的值,所以我需要小心跟踪回调中的引用。
我已经编写了一个蛮力解决方案,但我想学习一个更惯用或更干净的解决方案。
这是一些部分代码 -
var jsonItems = [];
items.forEach(function(item){
var jsonItem = {};
jsonItem.name = item.name;
item.getThings().then(function(things){
// or Promise.all(allItemGetThingCalls, function(things){
things.forEach(function(thing, index){
jsonItems[index].thingName = thing.name;
if(thing.type === 'file'){
thing.getFile().then(function(file){ //or promise.all?
jsonItems[index].filesize = file.getSize();
它非常简单,有一些简单的规则:
then
创建承诺时,将其返回- 您不返回的任何承诺都不会在外面等待。.all
它们- 这样它就会等待所有承诺,并且不会消除任何来自其中的错误。then
s 时,您通常可以在中间返回- then
链通常最多 1 级深。还有一些提示:
.map
映射比使用for/push
更好- 如果您使用函数映射值, map
可以让您简洁地表达一个一个应用操作并聚合结果的概念。Promise.all
比一个接一个地执行事物更好 - 每个都在下一个之前等待。好的,让我们开始吧:
var items = [1, 2, 3, 4, 5];
var fn = function asyncMultiplyBy2(v){ // sample async action
return new Promise(resolve => setTimeout(() => resolve(v * 2), 100));
};
// map over forEach since it returns
var actions = items.map(fn); // run the function over all items
// we now have a promises array and we want to wait for it
var results = Promise.all(actions); // pass array of promises
results.then(data => // or just .then(console.log)
console.log(data) // [2, 4, 6, 8, 10]
);
// we can nest this of course, as I said, `then` chains:
var res2 = Promise.all([1, 2, 3, 4, 5].map(fn)).then(
data => Promise.all(data.map(fn))
).then(function(data){
// the next `then` is executed after the promise has returned from the previous
// `then` fulfilled, in this case it's an aggregate promise because of
// the `.all`
return Promise.all(data.map(fn));
}).then(function(data){
// just for good measure
return Promise.all(data.map(fn));
});
// now to get the results:
res2.then(function(data){
console.log(data); // [16, 32, 48, 64, 80]
});
这是一个使用 reduce 的简单示例。 它串行运行,维护插入顺序,并且不需要 Bluebird。
/**
*
* @param items An array of items.
* @param fn A function that accepts an item from the array and returns a promise.
* @returns {Promise}
*/
function forEachPromise(items, fn) {
return items.reduce(function (promise, item) {
return promise.then(function () {
return fn(item);
});
}, Promise.resolve());
}
并像这样使用它:
var items = ['a', 'b', 'c'];
function logItem(item) {
return new Promise((resolve, reject) => {
process.nextTick(() => {
console.log(item);
resolve();
})
});
}
forEachPromise(items, logItem).then(() => {
console.log('done');
});
我们发现将可选上下文发送到循环中很有用。 上下文是可选的并且由所有迭代共享。
function forEachPromise(items, fn, context) {
return items.reduce(function (promise, item) {
return promise.then(function () {
return fn(item, context);
});
}, Promise.resolve());
}
您的承诺函数如下所示:
function logItem(item, context) {
return new Promise((resolve, reject) => {
process.nextTick(() => {
console.log(item);
context.itemCount++;
resolve();
})
});
}
我也经历过同样的情况。 我用两个 Promise.All() 解决了。
我认为这是一个非常好的解决方案,所以我在 npm 上发布了它: https ://www.npmjs.com/package/promise-foreach
我认为你的代码会是这样的
var promiseForeach = require('promise-foreach')
var jsonItems = [];
promiseForeach.each(jsonItems,
[function (jsonItems){
return new Promise(function(resolve, reject){
if(jsonItems.type === 'file'){
jsonItems.getFile().then(function(file){ //or promise.all?
resolve(file.getSize())
})
}
})
}],
function (result, current) {
return {
type: current.type,
size: jsonItems.result[0]
}
},
function (err, newList) {
if (err) {
console.error(err)
return;
}
console.log('new jsonItems : ', newList)
})
只是为了添加到所提供的解决方案中,在我的情况下,我想从 Firebase 获取多个数据以获取产品列表。 这是我如何做到的:
useEffect(() => {
const fn = p => firebase.firestore().doc(`products/${p.id}`).get();
const actions = data.occasion.products.map(fn);
const results = Promise.all(actions);
results.then(data => {
const newProducts = [];
data.forEach(p => {
newProducts.push({ id: p.id, ...p.data() });
});
setProducts(newProducts);
});
}, [data]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.