繁体   English   中英

我如何正确使用promise,以便我的代码不会嵌套?

[英]How can I properly use promises so my code isn't so nested?

这是我的代码。 它仍然非常嵌套。 如果有问题,我正在使用bluebird

Promise.each BrowseNodes, (BrowseNode) ->
  amazonClient.browseNodeLookup
    browseNodeId: BrowseNode.browseNodeId
  .then (lookupResult) ->
    childNodes = lookupResult[0].Children[0].BrowseNode
    Promise.each childNodes, (childNode) ->
      amazonClient.browseNodeLookup
        browseNodeId: childNode.BrowseNodeId
        responseGroup: 'TopSellers'
      .then (results) ->
        items = results[0].TopSellers[0].TopSeller

通常,要摆脱这种瀑布效应,您可以更改以下内容:

asyncService.doSomething()
.then(function(res) {
  asyncService.doSomethingElse(res)
  .then(function(secondRes) {
    asyncService.doAThirdThing(secondRes)
    .then(function(thirdRes) {
      // continue
    });
  });
});

对此:

asyncService.doSomething()
.then(function(res) {
  return res;
})
.then(function(res) {
  return asyncService.doSomethingElse(res);
})
.then(function(secondRes) {
  return asyncService.doAThirdThing(secondRes);
})
.then(function(thirdRes) {
  // etc.
});

该解决方案之所以有效,是因为Promise方法返回自身的Promise。

这只是一个语法上的实现细节,但是代码做同样的事情。

如果您将ES6与CoffeeScript一起使用,请尝试使用co之类的库来利用看起来同步的异步代码(通过使用生成器)。

您还可以使用诸如promise-waterfall之类的东西,或者查看是否有任何可用于即将到来的ES7 async / await的回填库。

编辑

处理Promise.each

.then(function() {
  return Promise.each(/* do stuff */);
})
.then(function(result) {
  // do stuff
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM