如何正确使用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瀑布的东西,或者查看是否有任何回填库可用于即将推出的ES7 async/await。
编辑
处理Promise.each
:
.then(function() {
return Promise.each(/* do stuff */);
})
.then(function(result) {
// do stuff
});
相关文章:
- 如何打印嵌套对象的所有值
- querySelector/getElementByClassName嵌套项的顺序
- 带嵌套json的下划线js查找
- 更改嵌套对象的父子相关id
- 带有嵌套状态的Angular ui路由器和后退按钮
- 更新嵌套对象的多个字段
- javascript中嵌套括号的regex
- ExtJS 4.1-检索嵌套JSON的hasOne信息
- Chai深度包含了对嵌套对象的断言
- 在JSP中获取嵌套形式的select列表值
- 将JS对象数组转换为嵌套形式的最有效方法
- 三层嵌套引号的问题
- 编码为深度嵌套对象的 HTML 字段 json
- Parse.com 检索嵌套对象的值
- Angular UI Router-在不了解第二级嵌套视图的情况下更改第三级嵌套视图
- javascript中嵌套对象的深度复制数组
- 我有一个嵌套if的函数.我怎样才能做出'这个'指向构造函数.父
- 如果我插入到嵌套出口的链接,Ember网站就会崩溃
- Ng-model只有在我嵌套相同的控制器时才能工作
- Javascript:如果我不知道嵌套对象的键,我该如何访问该对象中的值