Promise.all with nested Promise.all

I have nested arrays, I can get promises for a level 2 array, but I don't know how to implement top-level completion then.

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

for example, if it resultshas two or more elements, and each itemhas 10 or more URLs to retrieve, how to implement then [Promise.all][1]for all promises. Natural solution please.

Mostly for the proper handling of nested promises arrays.

Data structure:

var result = [
    {
        urls: [
            {href: "link1"},
            {href: "link2"},
            {href: "link3"}
        ]
    },
    {
        urls: [
            {href: "link4"},
            {href: "link5"},
            {href: "link6"}
        ]
    }
];
+4
source share
2 answers

Use mapinstead forEachand wrap it in another challenge Promise.all.

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);
});
Run codeHide result

. , ,

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);
});
Hide result
+8

, Promise.all

var urls = result.map(function(entity) => {return entity.urls;}) 
urls = [].concat.apply([], urls)

return Promise.all(urls.map(function(item){
    return requestURL(item.href);
}));
-1

Source: https://habr.com/ru/post/1648190/


All Articles