2 回答
TA贡献1873条经验 获得超9个赞
这取决于您对“问题”的含义,但是这段代码:
async function f2() {
await f1().catch(ex => { /* ... code in catch ... */ }) // this is what I mean
}
相当于:
async function f2() {
try {
await f1()
} catch (ext) {
/* ... code in catch ... */
} // this is what I mean
}
.catch正如您所说,使用它而不是按try-catch原样使用可能很有用- 并非在每种情况下 - 都可以使您的代码更具可读性。但是您需要始终考虑是否.catch是可读性的正确选择。如果您将它用于可恢复的错误处理,它会很好地工作。
TA贡献1859条经验 获得超6个赞
我想你要找的是这个
function f1(){
return new Promise((res,rej)=>{
rej(1)
})
}
async function f2(){
try {
const response = await f1();
// use the response from f1()
} catch(err) {
throw new Error(err);
}
}
f2()
沿着这些思路的东西async/await是承诺的包装,允许您编写看起来同步的代码。否则你会看
function f2(){
let response;
f1().then(res => {
response = res
})
.catch(err => {
throw Error(err)
});
}
添加回答
举报
