如何正确使用promise,使我的代码;不要这么嵌套

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

本文关键字:嵌套 我的 何正确 promise 代码      更新时间:2023-09-26

这是我的代码。它仍然是嵌套的。如果重要的话,我正在使用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瀑布的东西,或者查看是否有任何回填库可用于即将推出的ES7 async/await。

编辑

处理Promise.each:

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