【问题标题】:How can I properly use promises so my code isn't so nested?如何正确使用 Promise,使我的代码不那么嵌套?
【发布时间】:2016-03-02 03:26:32
【问题描述】:

这是我的代码。它仍然非常嵌套。如果这很重要,我正在使用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

【问题讨论】:

标签: javascript coffeescript promise bluebird


【解决方案1】:

一般来说,为了摆脱这种瀑布效应,您可以进行如下更改:

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

【讨论】:

    猜你喜欢
    • 2019-03-12
    • 2016-10-01
    • 2019-03-07
    • 1970-01-01
    • 2016-07-26
    • 1970-01-01
    • 2013-04-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多