我一直在阅读有关在Promises中使用async/await
而不是经典的.then()
的信息,但仍有一些我不理解的地方。
我知道您可以用.then().catch()
和async/await
替换经典的try and catch
,但是它们可以像处理相同的一样处理exceptions
和rejects
。
示例:
async function func1() {
return new Promise((resolve, reject) => {
//throw new Error("error");
reject("rejected");
});
}
async function func2() {
try {
const message = await func1();
console.log(message);
} catch(e) {
console.log(e);
}
}
func2();
reject
和throw new Error
都将落入catch
块中,但是Promises也有下一个句柄:
then(funcResolve, funcReject).catch(funcCatch)
,但async/await
将reject
和errors
视为相同。
是否可以通过async/await
和error
与reject
进行区分?
答案 0 :(得分:1)
基于Chrome浏览器中的少量实验,看来promise().then(funcResolve, funcReject).catch(funcCatch)
在功能上等同于几乎
async function run() {
try {
try {
const result = await promise();
} catch(e) {
// funcReject code here
}
// funcResolve code here
} catch(e) {
// funcCatch code here
// this catches errors generated in funcReject and funcResolve
}
}
唯一的区别是,在Promise版本中,funcResolve不会在funcReject之后运行,但是在我的异步代码中会运行。
如果您绝对需要区分异步操作的错误和同步操作的错误,您仍然可以获得相同的结果。例如,您可以确保异步操作返回一个扩展了Error的自定义类,并在您的catch中检查该类
class AsyncError extends Error{}
// in your async code, make sure you transform all errors into AsyncErrors
try { promise() } catch(e) {
if (e instanceof AsyncError) {} else {}
}