我怎样才能正确使用承诺,使我的代码不那么嵌套?
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 方法 return 承诺自己。
这只是一个语法实现细节,但代码做同样的事情。
如果您将 ES6 与 CoffeeScript 一起使用,请尝试使用像 co 这样的库来利用看起来同步的异步代码(通过使用生成器)。
您也可以使用 promise-waterfall 之类的东西,或者查看是否有任何可用于即将推出的 ES7 的回填库 async/await。
编辑
处理Promise.each
:
.then(function() {
return Promise.each(/* do stuff */);
})
.then(function(result) {
// do stuff
});
这是我的代码。它仍然是非常嵌套的。如果重要的话,我正在使用 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 方法 return 承诺自己。
这只是一个语法实现细节,但代码做同样的事情。
如果您将 ES6 与 CoffeeScript 一起使用,请尝试使用像 co 这样的库来利用看起来同步的异步代码(通过使用生成器)。
您也可以使用 promise-waterfall 之类的东西,或者查看是否有任何可用于即将推出的 ES7 的回填库 async/await。
编辑
处理Promise.each
:
.then(function() {
return Promise.each(/* do stuff */);
})
.then(function(result) {
// do stuff
});