1

I have found the following use case while working with promises. I am writing CoffeeScript for concision but the reading for JavaScript developers should be straight forwards

getUserName().then (userName) ->
  getRelatedCompany(userName).then (relatedCompany) ->
    registerConnexion(userName, relatedCompany)

In the above all request depend of the above results of the previous ones. What's the proper way to solve this to get something like this:

getUserName().then (userName) ->
  getRelatedCompany(userName)
.then (relatedCompany) ->
  # in that example, userName would be undefined here but there's less callbackception
  registerConnexion(userName, relatedCompany) 

EDIT: I am using bluebird as promise library.

Benjamin Gruenbaum
  • 270,886
  • 87
  • 504
  • 504
AsTeR
  • 7,247
  • 14
  • 60
  • 99

1 Answers1

1

You can use promises as proxies that represent values:

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

In bluebird, this is even simpler and becomes:

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

Since .join was designed for this use case in mind.

Benjamin Gruenbaum
  • 270,886
  • 87
  • 504
  • 504