[英]Avoiding callback hell in promises using nodejs
我已經使用諾言在nodejs中編寫了大約六個函數,我想真正發布所有代碼,相反,我將發布一個模擬示例,以便我可以簡潔地封裝我的問題。 所以說我下面有2個功能:
foo = () => {
return new Promise( ( r , rj ) => {
setTimeout( () => {
r('DONE');
}, 3000 );
});
}
和
bar = () => {
return new Promise( (r , rj) => { r('ALL DONE !') } )
}
現在,我想避免回調地獄,並執行以下操作:
foo().then( (resp) => console.log(resp) ).bar()
相反,我被迫這樣做:
foo().then( (resp) => { console.log(resp); bar() } )
所以基本上,到目前為止,在我的生產代碼中,我有類似下面的內容(只是為了給您一個想法):
let uploadToVault = ( INPUT_DIR , VOLT_CRED ) => {
INPUT_DIRECTORY = INPUT_DIR;
VOLT_CREDENTIALS = VOLT_CRED;
volt_APILogin().then( () => {
volt_getProduct().then( () => {
volt_CreatePresentation().then( (resp) => {
console.log(resp);
volt_uploadSlides().then( (resp) => {
console.log(resp);
volt_bindSlide().then( (resp) => {
console.log(resp);
});
});
});
});
});
}
現在我該如何用鏈式格式而不是在回調中編寫此格式?
這個想法將是始終兌現承諾:
volt_APILogin()
.then(() => {
return volt_getProduct();
})
.then(() => {
return volt_CreatePresentation();
})
.then((resp) => {
console.log(resp);
return volt_uploadSlides();
})
.then((resp) => {
console.log(resp);
return volt_bindSlide();
})
.then((resp) => {
console.log(resp);
return Promise.resolve('just for fun');
})
.then((resp) => {
console.log("This round is", resp);
});
然后,如果您需要在鏈中使用中間值,只需將它們收集到鏈外的變量中即可。
提示是檢查異步/等待語法。 基本上可以編寫看起來像同步代碼的異步代碼。
因此,如果您具有以下功能:
bar = () => {
return new Promise( (r , rj) => { r('ALL DONE !') } )
}
然后您可以這樣稱呼它:
let fizz = async () => {
const result = await bar();
console.log(`Bar said: ${result}`);
};
為了進行錯誤處理,您可以將正在等待的函數調用包裝在try-catch塊中:
try {
const result = await bar();
console.log(`Bar said: ${result}`);
} catch {
// Handle the error
}
查看此鏈接以獲取更多信息: https : //javascript.info/async-await (或者只是Google“ js async await”,您還會發現更多的內容:))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.