通常需要在稍后的步骤中使用从某个承诺返回的某些信息。一个例子是数据库连接:
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
为了避免这种情况,我通常会这样做:
var db;
database.connect()
.then(dbConnection => db = dbConnection)
.then(() => runStepOne(db))
// access global
.then(returnValOfStepOne => runStepTwo(returnValOfStepOne, db))
// access global again
问题是,这是对还是错?这个问题有更好的模式吗?