一个异步操作迭代完成再去执行下一个异步操作
将异步等待时间,当做参数 time传入方法中,通过 resolve()
输出Symbol.asyncIterator
异步的可迭代协议,配合 for-await-of 进行异步函数的迭代
function getPromise(time) {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve({
value: time,
done: false
})
}, time);
})
}
const arr = [getPromise(1000), getPromise(5000), getPromise(3000)]
arr[Symbol.asyncIterator] = function () {
let nextIndex = 0
return {
next() {
return nextIndex < arr.length ? arr[nextIndex++] :
Promise.resolve({
value: undefined,
done: true
})
}
}
};
async function test() {
for await (let item of arr){
console.log(item)
}
}
test()