Promise.prototype.then()行为

时间:2017-04-20 13:59:08

标签: javascript node.js promise es6-promise

我有这个承诺:

var seasonalityArray;   

    ...

aService.gettingAnalysis(site, cohortKey)
            .then(function (result) {
                let date = moment();
                seasonalityArray = result.cooling.getSeasonMonths(date);
            })
            , function (error) {
                console.error('An error occurred', error);
            };


const totalAccounts = _.size(report.asModel().accountNumbers);

const warnings = _.compact(_.map(seasonalityArray, function (monthLabel) {

               ...

}));

...

   aService.gettingAnalysis = function (site, Key) {
        return Promise.all([
            aService.findingHeat(site, Key),
            aService.findingCool(site, Key)
        ]).spread(function (heating, cooling) {
            return { heating: heating, cooling: cooling };
        });
    };

seasonalityArray内部变量中,必须获得一个月份数组(例如['June','July','August']),然后才会使用该数组。

我在调试每个步骤时发现的问题是,在它与aService.gettingAnalysis一致之后,它不会输入。then()以及之后的所有代码但跳转到设置totalAccounts然后在seasonalityArrayundefined的情况下输入警告。

有没有办法让它进入then()内部,或至少在将变量用作undefined之前设置该变量?

2 个答案:

答案 0 :(得分:2)

aService.gettingAnalysis(site, cohortKey)
        .then(function (result) {
            let date = moment();
            seasonalityArray = result.cooling.getSeasonMonths(date);
            //now we can do the rest
            const totalAccounts = _.size(report.asModel().accountNumbers);

            const warnings = _.compact(_.map(seasonalityArray, function (monthLabel) {}));
        })
        , function (error) {
            console.error('An error occurred', error);
        };

如何从异步调用返回可能重复,因此您可以阅读更多有关Promises的内容。 承诺不是要立即执行,而是 somewhen 。所以你不能简单地把代码放在它后面,并期望它在承诺完成后执行。您可以查看 async && 等待 ...

答案 1 :(得分:2)

如果您在使用数据时需要数据,则必须在承诺解决后使用它。您可以将需要完成的工作移至 功能

var seasonalityArray;

...

aService.gettingAnalysis(site, cohortKey)
    .then(function(result) {
        let date = moment();
        seasonalityArray = result.cooling.getSeasonMonths(date);
        doStuff();
    })

function doStuff() {
    const totalAccounts = _.size(report.asModel().accountNumbers);

    const warnings = _.compact(_.map(seasonalityArray, function(monthLabel) {
        ...
    }));

}

我废除了"全球"反而是承诺链。

aService.gettingAnalysis(site, cohortKey)
    .then(function(result) {
        let date = moment();
        seasonalityArray = result.cooling.getSeasonMonths(date);
        return seasonalityArray;
    }).then(doStuff)

function doStuff(seasonalityArray) {
    const totalAccounts = _.size(report.asModel().accountNumbers);

    const warnings = _.compact(_.map(seasonalityArray, function(monthLabel) {
        ...
    }));

}

then返回promise,其中已解析的数据是then返回的数据。