async await
- async 和 await 是一种更加优雅的异步编程解决方案,是 Promise 扩展
- async 让我们写起 Promise 像同步操作
async await 基本语法
- 前面加 async 的函数,在执行后都会自动返回一个 Promise 对象
async function foo() {
return 'es'
}
console.log(foo())
- await 后面需要跟异步操作,否则没有意义
- await 后面的 Promise 对象不必写 then,因为 await 的作用之一就是获取后面 Promise 对象成功状态传递出来的参数
function timeout() {
return new Promise(resolve => {
setTimeout(() => {
console.log(1)
resolve()
}, 1000)
})
}
// 不加 async 和 await 是2、1 加了是 1、2
async function foo() {
await timeout()
console.log(2)
}
foo()
async await 对失败处理
- Promise 对象成功状态 fulfilled 和失败状态 rejected 里面的 resolve() 和 reject() 返回的值,只能通过 then() 或 catch() 获取
- async 函数中使用 await,await 后面跟的代码会变成同步任务,只有等 await 后面的 Promise 执行完成得到结果才会继续下去,await 就是等待的意思
function timeout() {
return new Promise((resolve, reject) => {
setTimeout(() => {
// resolve('success')
reject('error')
}, 1000)
})
}
async function foo() {
return await timeout()
}
foo().then(res => {
console.log(res)
}).catch(err => {
console.log(err) // error
})
案例:需要发送多个请求,后面请求发送总是需要依赖上一个请求返回的数据
- 既可以用 Promise 链式调用来解决,也可以用 async/await 来解决,后者更简洁
- await 只能在 async 标记的函数内部使用,单独使用会触发 Syntax error
// 封装 ajax 请求函数
function ajax(url, successCallback, failCallback){
let xmlhttp
if(window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest()
} else {
xmlhttp = new ActiveXObject('Microsoft.XMLHTTP')
}
xmlhttp.open('GET', url, true)
xmlhttp.send()
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState === 4 && xmlhttp.status === 200){
const obj = JSON.parse(xmlhttp.responseText)
successCallback(obj)
} else if(xmlhttp.readyState === 4 && xmlhttp.status === 404) {
failCallback(xmlhttp.statusText)
}
}
}
// 封装 Promise 请求函数
function request(url){
return new Promise((resolve, reject) => {
ajax(url, res => {
resolve(res)
}, err => {
resolve(err)
})
})
}
const url1 = 'http://jsonplaceholder.typicode.com/users'
const url2 = 'http://jsonplaceholder.typicode.com/todos'
const url3 = 'http://jsonplaceholder.typicode.com/photos1'
// 使用 async await 发送请求
async function getData(){
const res1 = await request(url1)
console.log(res1)
const res2 = await request(url2)
console.log(res2)
const res3 = await request(url3)
console.log(res3)
}
getData()