[英]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.