參考文章: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),陸續輸出各個字母