0

It's common that some information, returned from a certain promise, need to be used in a later step. One example is db connection:

database.connect()
    .then(dbConnection => runStepOne(dbConnection))
    // runStepOne is async and needs db
    .then(returnValOfStepOne => runStepTwo(returnValOfStepOne, dbConnection))
    // runStepTwo needs both stepOne's return value and db - this is totally reasonable
    // but dbConnection is not available here anymore

To circumvent this, I usually do:

var db;
database.connect()
    .then(dbConnection => db = dbConnection)
    .then(() => runStepOne(db))
    // access global
    .then(returnValOfStepOne => runStepTwo(returnValOfStepOne, db))
    // access global again

Question is, is this right or wrong? Are there any better patterns for this problem?

Boyang
  • 2,520
  • 5
  • 31
  • 49
  • 1
    You don't need global variables ever – Mulan Jul 28 '16 at 23:50
  • Yes, it is bad practice to set globals, but it is OK (in some cases) to set a private variable in a higher scope to enable sharing. See [the dup](http://stackoverflow.com/questions/28714298/how-to-chain-and-share-prior-results-with-promises) for a lot more options. – jfriend00 Jul 29 '16 at 00:00

0 Answers0