Promise链不按预期顺序执行 – nodejs

我有一个4个承诺链,最后1个function。 最终的function在链中先前的承诺已经解决之前执行。

有人可以向我解释为什么这可能会发生?

这是承诺链:

updateGdax(db) .then(updateBitstamp(db)) .then(updateBitfinex(db)) .then(updatePoloniex(db)) .then(coinMarketData.updateCoinMarketData(db)) .then(addRates(db)); //this function is executing after the first promise in the chain. 

我希望每个函数都能在之前列出的函数之后执行,所以addRates(db)应该最后执行。

如果需要进一步分析,我可以从promise函数中发布代码,但是我真的只想了解为什么会发生这种情况,因为我的理解是,除非链中的前一个promise已经解决,否则promise链中的函数将不会执行。

除非在调用中的那些更新函数被部分地应用(除非它们返回一个函数),否则在调用之前它们被执行。 你需要把它们包装在一个匿名函数中,让它们按顺序执行。 做另一个答案,或使用胖箭头:

 updateGdax(db) .then(()=>updateBitstamp(db)) .then(()=>updateBitfinex(db)) .then(()=>updatePoloniex(db)) .then(()=>coinMarketData.updateCoinMarketData(db)) .then(()=>addRates(db)); 

如果你的更新函数可以被重写,在完成之后返回db,那么你可以像这样重写这些调用,免费的风格:

 updateGdax(db) .then(updateBitstamp) .then(updateBitfinex) .then(updatePoloniex) .then(coinMarketData.updateCoinMarketData) .then(addRates); 

每个function,然后看起来像这样:

 function updateGdax(db) { return db.doSomething().then(()=> db) } 

按照这种模式,你有自己一些漂亮的javascript。

并且看看nodejs 8中包含的新的asynchronous/等待。它更直观:

 async function main() { await updateGdax(db) await updateBitstamp(db) await updateBitfinex(db) await updatePoloniex(db) await coinMarketData.updateCoinMarketData(db) await addRates(db) } main().catch(e => console.error(e)) 

尝试下面的方法,

 updateGdax(db) .then(function(){ return updateBitstamp(db) }).then(function (){ return updateBitfinex(db); }).then(function() { return updatePoloniex(db); }).then(function(){ return coinMarketData.updateCoinMarketData(db) }).then(function(){ return addRates(db); }).catch(function(err){ console.log(err); }); 

希望这会工作。 如果任何函数正在返回任何值,并且如果您想在后续函数中使用它,那么在函数()中使用的那个值将在那里使用。 请参阅: https : //strongloop.com/strongblog/promises-in-node-js-an-alternative-to-callbacks/