async await 和 Promise 的区别
async
async 是用来定义异步函数的,打印函数返回值是Promise对象,可以用
.then
的方式来调用。
//执行async函数,返回的都是Promise对象
async function test1() {
return 1;//相当于return Promise.resolve(1)
}
async function test2() {
return Promise.resolve(2);
}
const result1 = test1();
const result2 = test2();
console.log(result1);//Promise对象
console.log(result2);//Promise对象
//async 定义的函数可以用then的方式调用
async function test3() {
const p3 = Promise.resolve(3);
//.then 的方式
p3.then(data => {
console.log('data3', data)//3
})
}
test3()
await
await要放在async定义的异步函数中,后边一般跟的是Promise 的表达式,对应Promise.then成功的情况。
//Promise.then成功的情况对应await
async function test3() {
const p3 = Promise.resolve(3);
//.then 的方式
p3.then(data => {
console.log('data3', data)//3
})
//await的方式
const data3 = await p3;
console.log('data3', data3)//3
//.then和await打印的值相同,可以说明Promise.then成功的情况对应await
}
test3()
如果 await后面跟的是Promise.reject()的情况,那就要使用try catch进行捕获
//Promise.catch 异常的情况对应try...catch
//异常不能被捕获的情况
async function test6() {
const p6 = Promise.reject(6);
const data6 = await p6;
console.log(data6);//Uncaught (in promise) 6 —— 异常不能被捕获
}
test6()
async function test7() {
const p7 = Promise.reject(7);
try {
const data7 = await p7;
console.log(data7);
} catch (err) {
console.error(err);//7 —— 异常可以被捕获
}
}
test7()
async await 和 Promise 的区别
Promise | async await |
---|---|
ES6 | ES7 |
可以通过.catch进行捕获 | 必须自己定义catch |
方法多:all,race等 |
以上就是async await 和 Promise 的区别,请大家关注《前端面试题》专栏。
我会将自己平时项目中常见的问题以及笔试面试的知识在CSDN与大家分享,一起进步,加油。