可以用同步编程的方式去写异步代码。
- async await是基于promise的语法糖,使用ascync关键字的函数会默认返回promise.resolve,引擎在遇到await关键字的时候会等待关键字后面的代码执行完毕后继续向下执行。需要注意的是await不能单独使用必须配合async一起使用。
- async await可以用来优化Fetch
- 下面的fetch的输出顺序并不是每次都是一样而是哪个请求响应的速度快就先输出哪个
const url = "https://xxx.com"
fetch(`${url}/1/`)
.then(res => res.json())
.then(json => json.data)
.then(data => {
console.log(data)
})
fetch(`${url}/2/`)
.then(res => res.json())
.then(json => json.data)
.then(data => {
console.log(data)
})
fetch(`${url}/3/`)
.then(res => res.json())
.then(json => json.data)
.then(data => {
console.log(data)
})
现在我们用async await来进行优化使得每次的输出顺序都是一致的
let bb = async () => {
const url = "https://xxx.com"
try {
let responses = await Promise.all(
[fetch(`${url}/1`),fetch(`${url}/2`),fetch(`${url}/3`)])
//json()会返回一组promise对象,所以要再次调用promise.all
let jsons = responses.map(response => { response.json() })
let values = await Promise.all(jsons)
values.map(value => {
console.log(value.data)
}
} catch (error) {
console.log(error)
}
}