参考文章:https://blog.csdn.net/songxiugongwang/article/details/83243311
异步迭代器结构如下图:
const obj = {
[Symbol.asyncIterator]: () => {
const items = [`j`, `u`, `s`, `t`, `j`, `a`, `v`, `a`, `c`];
return {
next: () => {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve({
done: items.length === 0,
value: items.shift()
})
}, 1000)
})
}
}
}
}
遍历迭代器:
async function process(array) {
for await (let i of array) {
console.log(i + 'abc') //i是返回的value值
}
}
调用就是process(obj),陆续输出各个字母
另一种比较常用的方式:
var fetch = function (t) {
return new Promise((resolve, reject) => {
setTimeout(resolve, 1000, t);
})
}
async function process(array = [1, 2, 3]) {
for (const i of array) {
await fetch(i)
console.log(i)
}
}
process()
两个的区别在于一个加在了for里面,一个在外面