let arr = [8, 4, 7]
function timeout(time) {
return new Promise(function (resolve, reject) {
setTimeout(function () {
resolve(time)
}, time * 1000)
})
}
1.第一种
async function test(arr) {
for await (let item of arr) {
timeout(item).then(res => {
console.log(res);
})
}
}
按延迟的顺序执行4,7,8,总共8s,4s时输出4,7s时输出7,8s时输出8,跟不加async…await没啥区别
2.第二种
function test1(arr) {
arr.forEach(async item => {
const res = await timeout(item)
console.log(res);
});
}
按延迟的时间长短顺序执行4,7,8,分别延迟4s,7s,8s,总共21s
3.第三种
async function test2(arr) {
for (let item of arr) {
const res = await timeout(item)
console.log(res);
}
}
按数组的顺序执行 8,4,7,分别延迟8s,4s,7s,总共21s ,所以第三种才是最终想要的方案
1.为什么同样是遍历,输出结果却不一样呢?
因为 for…of 内部处理的机制和 forEach 不同,forEach 是直接调用回调函数,for…of 是通过迭代器的方式去遍历。
// 参考下 Polyfill 版本的 forEach,简化后的伪代码:
while (index < arr.length) {
callback(item, index) //我们传入的回调函数
}
async function test3(arr) {
const iterator = arr[Symbol.iterator]() //for of会自动调用遍历器函数
let res = iterator.next()
while (!res.done) {
const value = res.value
const res1 = await timeout(value)
console.log(res1)
res = iterator.next()
}
}
test3(arr)