![](/img/trans.png)
[英]Wrong executing order with NodeJS callback based function in promise chain
[英]Promise chain not executing in expected order - nodejs
我有一个由4个诺言组成的链,最后有1个职能。 最终功能在链中先前的承诺解决之前执行。
有人可以向我解释为什么会这样吗?
这是承诺链:
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链中的函数将不会执行。 。
除非部分应用了then调用中的那些更新函数(除非它们返回一个函数),否则它们将在then调用之前被执行。 您需要将它们包装在一个匿名函数中,以便按顺序执行它们。 按照其他答案说的做,或使用粗箭头:
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 updateGdax(db) {
return db.doSomething().then(()=> db)
}
按照这种模式,您将拥有一些漂亮的javascript。
并查看一下nodejs 8中包含的新async / await。它更加直观:
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);
});
希望这会起作用。 如果任何函数返回任何值,并且要在后续函数中使用该值,则在内部使用的以下function()中传递该值。 请参阅: https : //strongloop.com/strongblog/promises-in-node-js-an-alternative-to-callbacks/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.