Promise.all 与嵌套的 Promise.all [英] Promise.all with nested Promise.all

查看:48
本文介绍了Promise.all 与嵌套的 Promise.all的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我嵌套了数组,我能够检索第二级数组的承诺,但不确定如何在顶级完成后实现 then.

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);
    }));
});

例如,如果 results 有两个或更多项目,并且每个 item 有 10 个或更多 url 来获取,我们将如何实现 then[Promise.all][1] 所有的承诺.请使用本机解决方案.

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.

基本上是为了以正确的方式处理嵌套的 Promise 数组.

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

数据结构:

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

推荐答案

使用 map 而不是 forEach,并将其包裹在另一个 Promise.all 中代码>调用.

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);
});

这篇关于Promise.all 与嵌套的 Promise.all的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆