我的问题是,将.catch与async await一起使用会导致问题吗?
例如:
function f1() {
return new Promise((res, rej) => {
rej(1)
})
}
async function f2() {
await f1().catch(ex => { }) // this is what I mean
}
f2()
这取决于你对"问题"的意思,但这段代码:
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
是否是可读性的正确选择。如果您将它用于可恢复的错误处理,它会很好地工作。
我想你要找的是这个
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
的东西是promise的包装器,它允许您编写看起来同步的代码。否则你会看到
function f2(){
let response;
f1().then(res => {
response = res
})
.catch(err => {
throw Error(err)
});
}