我在使用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);
});
});
});
});
});
}
现在,我怎么能用更多的链式格式写这个,而不是在回调中写这个?
我们的想法是永远回报一个承诺:
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);
});
然后,如果有中间值,您需要使用链,只需将它们收集到链外的变量。
提示是检查async / await语法。它基本上可以编写看起来像同步代码的异步代码。
所以,如果你有这个功能:
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等待”,你会发现更多:))