在Promise中,是通过catch的方式来捕获异常,而当使用async时,则通过try/catch来捕获异常.
function fn() {
return new Promise((resolve, reject)=>{
setTimeout(() => {
reject("some error");
}, 1000);
})
}
const fn = async ()=>{
try {
await fn();
}catch(e) {
console.log(e);
}
}
foo();
如果有多个await函数,那么只返回第一个捕获异常
function fn() {
return new Promise((resolve,reject)=>{
setTimeout(()=>{
reject("some error");
}, 1000);
})
}
function fn2() {
return new Promise((resolve, reject)=>{
setTimeout(()=>{
reject("some error fn2");
},1000);
})
}
const foo = async () => {
try {
await fn1();
await fn2();
}catch(e){
console.log(e)
}
}
foo();
在实践中遇到异步场景最多的就是接口的请求,因此这里就以Jquery中$.get为例,简单展示一下.
const clickUserInfo = () => $.get("xxxx/api/xx");
const clickHandler = async() => {
try {
const res = await getUserInfo();
console.log(res);
}catch(e) {
//
}
}