Promise.prototype.then()行为

我有这个承诺:

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 }; }); }; 

seasonalityArrayvariables里面,它必须得到一个数组(例如['June','July','August'] ),之后会被使用。

我在debugging每一步时发现的问题是,在进入aService.gettingAnalysis行之后,它不会进入。 then()和所有的代码之后,但它跳转到设置totalAccounts ,然后进入警告与seasonalityArray undefined

有没有办法让它进入内部then()或至less设置该variables之前,它使用undefined

 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); }; 

如何从asynchronous调用返回可能的重复,所以你可以读一点关于承诺。 一个承诺现在不是要执行,而是一些时候 。 所以你不能简单地把代码放在它后面,并期望它在Promise完成之后执行。 你可以看看asynchronous && 等待

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

 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 ,解决的数据就是那个返回的数据。