async
- async函数是对generator函数的改进
- 内置执行器,generator函数的执行需要执行器
- 更好的语义
- 更广的适用性,await命令后面可以跟Promise(异步)和原始类型(同步)
- 返回值是Promise而不是Iterator对象,方便后续操作
- 错误处理
- async函数内部未捕获的错误会使,async返回Promise的状态变为rejected
- await命令后跟的Promise对象状态为rejected,会导致await命令报错,阻塞async函数后续执行
- 异步迭代器next()方法返回Promise对象,Promise对象fulfilled态后返回{value,done}对象
-
async generator*
生成异步遍历器
-
for await...of
遍历异步遍历器
-
yield*
展开异步遍历器
-
async iterable
interface AsyncIterable {
[Symbol.asyncIterator]() : AsyncIterator,
}
interface AsyncIterator {
next(value?: any) : Promise,
}
interface IterationResult {
value: any,
done: boolean,
}
tips
- async函数内部是继发的执行,但是async函数外部不是
// 按序请求并打印
var urlArr = ['https://www.baidu.com','https://www.vip.com','https://www.qq.com']
var func = async ()=>{
for(let url of urlArr){
let response = await fetch(url)
await new Promise(res=>setTimeout(()=>res(),2000))
let text = await response.text()
console.log('===='+text.substr(0,100))
}
}
func()
// 并发请求,按序打印
var func2 = async ()=>{
for (let textPromise of urlArr.map(async url=>{
let response = await fetch(url)
await new Promise(res=>setTimeout(()=>res(),2000))
return response.text()
})){
let text = await textPromise
console.log('===='+text.substr(0,100))
}
}
func2()