在promise中使用和设置全局变量是不好的做法

时间:2016-07-28 23:46:56

标签: javascript node.js design-patterns promise global-variables

通常需要在稍后的步骤中使用从某个承诺返回的某些信息。一个例子是数据库连接:

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

问题是,这是对还是错?这个问题有更好的模式吗?

0 个答案:

没有答案