一、什么是async :
async函数是 使用async 关键字声明的函数。async函数是 AsyncFunction 构造函数的实例, 并且其中允许使用 await 关键字。
二、async的作用;
async 和await 关键字让我们可以用一种更加简洁的方式写出基于Promise 的异步行为,无需刻意地链式调用Promise;
(下面让我们上代码感受一下:)
需求 : 调用 http1 再调用http2 (这里用setTimeOut模拟请求);
依次打印出 :1 ,http1 响应值, http2 响应值,3
function http1() {
return new Promise(resolve => {
setTimeout(() => {
resolve('请求成功1')
}, 2000)
})
}
function http2() {
return new Promise(resolve => {
setTimeout(() => {
resolve('请求成功2')
}, 2000)
})
}
如果不使用 async await , 只能使用 Promise上的 .then() 方法
console.log(1)
http1().then(res1 => {
console.log('res1', res1)
return http2()
}).then(res2 => {
console.log('res2', res2)
console.log(3)
})
使用async
async function runAsync() {
console.log(1)
let res1 = await http1()
console.log('res1', res1)
let res2 = await http2()
console.log("res2", res2)
console.log(3)
}
runAsync()