【问题标题】:Flatter calls using promises: avoiding callbackception [duplicate]使用承诺的奉承调用:避免回调接收 [重复]
【发布时间】:2015-02-04 00:38:15
【问题描述】:

我在使用 Promise 时发现了以下用例。我写 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) 

编辑:我使用 bluebird 作为 promise 库。

【问题讨论】:

    标签: javascript coffeescript promise bluebird


    【解决方案1】:

    您可以使用 Promise 作为代表值的代理:

    username = getUserName()
    company = username.then(getRelatedCompany)
    // assuming good promise lib, otherwise shim .spread of nest once
    connexion = Promise.all([username, company]).spread(registerConnexion) 
    

    在bluebird中,这更简单,变成:

    username = getUserName()
    company = username.then(getRelatedCompany)
    connexion = Promise.join(username, company, registerConnexion);
    

    因为.join 是专为这个用例而设计的。

    【讨论】:

    • 我使用 bluebird 作为 Promise 库。我已经编辑了您的答案以修复错字!谢谢!
    • @AsTeR 编辑以包含 Bluebird 的答案,很快就会更新。
    • 我猜你的 StackExchange 帐户描述是一种 rickroll ......你找到我了 ;) !
    猜你喜欢
    • 2019-09-18
    • 1970-01-01
    • 2017-02-09
    • 2016-06-16
    • 2016-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多