Wednesday, June 5, 2024
 Popular · Latest · Hot · Upcoming
157
rated 0 times [  161] [ 4]  / answers: 1 / hits: 41330  / 8 Years ago, mon, july 18, 2016, 12:00:00

I've nested arrays, I'm able to retrieve promises for the 2nd level array but not sure how to implement a then once top level finishes as well.



result.forEach(function(entity){ // outer list ???
return Promise.all(entity.urls.map(function(item){
return requestURL(item.href);
}));
});


for instance if results has two or more items and each item has 10 or more urls to fetch, how would we implement then of [Promise.all][1] for all the promises. Native solution please.



Basically to handle nested arrays of promises in a right way.



Data Structure:



var result = [
{
urls: [
{href: link1},
{href: link2},
{href: link3}
]
},
{
urls: [
{href: link4},
{href: link5},
{href: link6}
]
}
];

More From » node.js

 Answers
61

Use map instead of forEach, and wrap it inside another Promise.all call.





var arr = [
{subarr: [1,2,3]},
{subarr: [4,5,6]},
{subarr: [7,8,9]}
];
function processAsync(n) {
return new Promise(function(resolve) {
setTimeout(
function() { resolve(n * n); },
Math.random() * 1e3
);
});
}
Promise.all(arr.map(function(entity){
return Promise.all(entity.subarr.map(function(item){
return processAsync(item);
}));
})).then(function(data) {
console.log(data);
});





You can also use an immediately invoked generator. For example, to get flattened results,





var arr = [
{subarr: [1,2,3]},
{subarr: [4,5,6]},
{subarr: [7,8,9]}
];
function processAsync(n) {
return new Promise(function(resolve) {
setTimeout(
function() { resolve(n * n); },
Math.random() * 1e3
);
});
}
Promise.all(function*() {
for(var entity of arr)
for(var item of entity.subarr)
yield processAsync(item);
}()).then(function(data) {
console.log(data);
});




[#61330] Friday, July 15, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
luzv

Total Points: 178
Total Questions: 105
Total Answers: 114

Location: Palau
Member since Tue, May 30, 2023
1 Year ago
;