1. 背景
如果await
后面的异步操作出错,则会抛出异常,不继续执行后面的逻辑
例如:
async function test() {
console.log("test 开始")
let result=await new Promise<string>((resolve, reject) => {
setTimeout(() => {
reject("hello world");
}, 1000);
});
console.log("test 结束")
}
test();
//只会输出 test 开始,不会输出 test 结束
防止出错的方法,也是将其放在try...catch
代码块之中。
async function test() {
console.log("test 开始")
try {
let result=await new Promise<string>((resolve, reject) => {
setTimeout(() => {
reject("hello world");
}, 1000);
});
console.