![](/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.