# ❓ 输出以下代码运行结果,为什么?如果希望每隔 1s 输出一个结果,应该如何改造?注意不可改动 square 方法
const list = [1, 2, 3]
const square = (num) => {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(num * num)
}, 1000)
})
}
function test() {
list.forEach(async (x) => {
const res = await square(x)
console.log(res)
})
}
test()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# Coding
// 由于 forEach 是不能阻塞的,默认是请求并行发起,所以是同时输出1、4、9。
// function test() {
// list.forEach(async x=> {
// const res = await square(x)
// console.log(res)
// })
// }
// 串行 `for` or `for of`
async function test() {
for (let i = 0; i < list.length; i++) {
const element = list[i]
const res = await square(element)
console.log(res)
}
}
// 回调
async function test() {
if (list.length) {
const res = await square(list.shift())
console.log(res)
test()
}
}
// Promise 链式调用实现串行
function test() {
let promise = Promise.resolve()
list.forEach(async (x) => {
promise = promise.then(() => square(x).then((_) => console.log(_)))
})
}
test()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35