forEach传一个回调函数,给这个回调函数加async是阻止不了循环的,它是先按顺序循环3次,每次执行了一个square,然后等待三个setTimeout执行完毕,可以square加个时间参数,每次递增1000,或者改用for循环就不需要传时间参数了
const list = [1, 2, 3];
const square = (num,time) => {
return new Promise((resolve,reject) => {
setTimeout(() => {
resolve(num * num)
}, time);
});
}
function test() {
let time = 0
list.forEach(async x => {
time += 1000
const res = await square(x,time);
})
}
async function test2() {
for(let i = 0; i < list.length; i ++) {
const res = await square(i,1000);
console.log(res)
}
}
test()
test2()