使用承诺的扁平调用:避免回调

Flatter calls using promises: avoiding callbackception

本文关键字:回调 调用 承诺      更新时间:2023-09-26

我在处理承诺时发现了以下用例。我正在编写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是为这个用例而设计的。