我在使用promises的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);
});
});
});
});
});
}
现在我怎么能用更多的链式格式写这个,而不是在回调中写这个?
2 回答
我们的想法是永远回报承诺:
然后,如果有中间值,您需要使用链,只需将它们收集到链外的变量 .
提示是检查async / await语法 . 它基本上可以编写看起来像同步代码的异步代码 .
所以,如果你有这个功能:
然后你可以像这样调用它:
对于错误处理,您可以在try-catch块中包装等待函数调用:
查看此链接了解更多信息:https://javascript.info/async-await(或者只是谷歌"js async await",你会发现更多:))