使用承诺的扁平调用:避免回调
Flatter calls using promises: avoiding callbackception
我在处理承诺时发现了以下用例。我正在编写CoffeeScript以简洁明了,但JavaScript开发人员的阅读应该是直截了当的
getUserName().then (userName) ->
getRelatedCompany(userName).then (relatedCompany) ->
registerConnexion(userName, relatedCompany)
在上述所有请求中,所有请求都取决于前面的上述结果。解决这个问题的正确方法是什么,以获得这样的东西:
getUserName().then (userName) ->
getRelatedCompany(userName)
.then (relatedCompany) ->
# in that example, userName would be undefined here but there's less callbackception
registerConnexion(userName, relatedCompany)
编辑:我正在使用蓝鸟作为承诺库。
您可以使用承诺作为表示值的代理:
username = getUserName()
company = username.then(getRelatedCompany)
// assuming good promise lib, otherwise shim .spread of nest once
connexion = Promise.all([username, company]).spread(registerConnexion)
在蓝鸟中,这甚至更简单,变成了:
username = getUserName()
company = username.then(getRelatedCompany)
connexion = Promise.join(username, company, registerConnexion);
由于.join
是为这个用例而设计的。
相关文章:
- 成功回调永远不会被JSONP请求调用
- 为什么(如何)'这'从函数内部调用回调时发生更改
- 如何在点击超链接时调用fullcalendar回调
- 在初始函数完成之前调用回调函数
- 未为路由器应用程序调用Node.Js的回调
- 对中的函数调用进行排序是回调的唯一方法
- Node.js exec调用从不调用回调
- 如何从参数数组中调用回调
- 当我的单元测试失败时,回调被调用了两次
- 回调函数(如afterMove)不被调用
- 如何使用jQuery等待来自回调的异步调用
- FireFox webrtc createoffer,没有任何回调调用
- 如何识别函数是作为方法调用还是作为回调调用
- jquery方法不是从angular回调调用的
- 从回调调用asyncwait
- 你可以使用PhoneGap和iOS从本地代码(而不是回调)调用javascript函数吗?
- Backbone model.fetch()回调(调用setTimeout)中的作用域问题
- React.js:你用一个不可调用的回调调用了' setState '
- 从图表.js选项回调调用 TypeScript 函数
- 如何将js函数从异步调用转换为回调调用