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?
Aucun commentaire:
Enregistrer un commentaire