【问题标题】:Nested promises and how to get around em嵌套的 promises 以及如何绕过它们
【发布时间】:2016-11-05 09:32:17
【问题描述】:

我正在使用 promise 从 URL 中获取一些 JSON。返回的 JSON 包括返回 JSON 的新 URL 列表。由于嵌套的 Promise,我当前的实现失败了。

我需要做以下事情:

  1. 请求父 JSON url
  2. 请求每个子 JSON url
  3. 在每个子 promise 返回 JSON 后,我需要对子 JSON 和父 JSON 做一些事情。

我收到以下错误。

Warning: a promise was created in a handler at main.development.js:661:61 but was not returned from it

我的代码的简化版本:

myPromise(url)
  .then(response => {
    // process the data into an array of items
   items.forEach(item => {
      myPromise(item.url)
        .then(response2 => {
          // Do a thing here with data from response and response2
        });
    });
  });

【问题讨论】:

  • Array forEach 不支持 Promise.. 有 promise.all,但如果说你使用像 Bluebird Promise 之类的东西,它的 promise.mappromise.all 更灵活
  • 谢谢基思。我正在使用使用 Bluebird 的 request-promise,这很好!也就是说,我查看了 Promise.map bluebird 文档,并不太确定如何使用它来完成我需要的工作。你有任何文章或例子可以链接到我吗?
  • 地图的工作方式与普通的 javascript 地图非常相似,但可以处理承诺。我会复制你的代码,然后粘贴为答案

标签: javascript node.js promise


【解决方案1】:

这里我使用 Bluebird 地图完成了你的示例。

我还添加了并发选项,这非常方便.. 省略,将有点像 Promise.all,并将值设置为 1,如果你想串联所有的 Promise ..

myPromise(url)
  .then(response => {
    // process the data into an array of items
   return Promise.map(items, item => {
     return myPromise(item.url)
        .then(response2 => {
          // Do a thing here with data from response and response2
        });
    }, {concurrency:10});  //lets do a max of 10 promises at a time.
  });

【讨论】:

    【解决方案2】:

    你的错误实际上只是一个警告。这是有充分理由的;一个常见的错误是做这样的事情

    myPromise(url)
        .then(response => {
            somethingElseAsync(response);        
        })
        .then(myCallback);
    

    并期望在somethingElseAsync 完成工作后调用myCallback。据我所知,这不是您的情况,因为您没有收集孩子承诺的结果。

    要取消警告,您可以关注Keith's answer。作为奖励,您可以在链上添加另一个 Promise,当所有子 Promise 都已解决时,该 Promise 将解决。

    作为Promise.map 的替代方案,如果您可以同时生成所有子任务,则可以使用Promise.all,如下所示:

    myPromise(url).then(response => {
        return Promise.all(items.map(item => {
            return myPromise(item.url).then(response2 => {
                // handle response and response2, return some result
                return result;
            });
        }));
    }).then(results => {
        //    ^^^ an array of results returned from child promise callbacks
    }).catch(error => {
        // either the parent promise or one of the child promises has rejected
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-05
      相关资源
      最近更新 更多