async await的使用
注意async 和await是配套使用的当在其他普通函数中使用await会报语法错误
- async函数返回一个 Promise 对象
async function isProimse(){
// return 'isProimse' //then 接收成功 async函数内部return语句返回的值,会成为then方法回调函数的参数
throw new Error('异步执行失败'); //catch接收异常 async函数内部抛出错误,会导致返回的 Promise 对象变为reject状态,抛出的错误对象会被catch方法回调函数接收到
}
isProimse().then(resolve=>{
console.log(resolve); //接收成功
}).catch(error=>{
console.log(error); //接收异常
})
-
async和await配套使用
一般情况下,await命令后面是一个Promise对象
async function fun(resolve) {
let a = await new Promise((resolve, reject) => {
setTimeout(() => {
resolve('异步1')
}, 3000)
})
console.log('a异步执行完毕') //等待a promise 执行完毕后执行
let b = await new Promise((resolve, reject) => {
setTimeout(() => {
resolve('异步2')
}, 3000);
})
console.log('b异步执行完毕') //等待b promise 执行完毕后执行
throw new Error('异步执行失败'); // catch中接收失败
return a + b + '全部执行完毕' // then中接收成功
}
fun().then(res => {
console.log(res)
}).catch(error=>{
console.log(error);
})
个人总结 ES6中 async 和await 为异步提供了更好的一种代码方案,使异步的代码看起来像同步