ES9-For await of
# ES9-For await of
# 问题原因
当需要使用for循环进行多次网络请求
数组中的元素都是promise
对象,是没有办法遍历的。
function test1(time) {
return new Promise((resolve, reject) => {
setTimeout(function () {
resolve(time)
},time)
})
}
function test2() {
let arr = [test1(2000), test1(1000), test1(3000)]
for(let item of arr) {
console.log(Date.now(), item.then(console.log))
}
}
test2()
// 1597047404040 Promise {<pending>}
// 1597047404040 Promise {<pending>}
// 1597047404040 Promise {<pending>}
// 1000
// 2000
// 3000
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# 如何可以解决这种问题?
将test2函数前面添加async,并在for-of遍历的时候给每个元素前面添加await,每个对象等待结束之后再执行下一个。
function test1(time) {
return new Promise((resolve, reject) => {
setTimeout(function () {
resolve(time)
},time)
})
}
async function test2() {
let arr = [test1(2000), test1(1000), test1(3000)]
for(let item of arr) {
console.log(Date.now(), await item.then(console.log))
}
}
test2()
// 2000
// 1597047766221 undefined
// 1000
// 1597047768223 undefined
// 3000
// 1597047768224 undefined
分析输出结果:先执行了await后面的then,返回2000之后
执行console.log返回时间戳
然后await的返回值是空,所以返回undefined
虽然因为await让for-of暂停了,但是执行的顺序和我们想要的还是不一样
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
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
# 最终的解决方式 —— For await of
test2函数前面还要添加async
关键字,对for-of
进行改进
function test1(time) {
return new Promise((resolve, reject) => {
setTimeout(function () {
resolve(time)
},time)
})
}
async function test2() {
let arr = [test1(2000), test1(100), test1(3000)]
for await(let item of arr) {
console.log(Date.now(), item)
}
}
test2()
// 1597048677429 2000
// 1597048677429 100
// 1597048678429 3000
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
上次更新: 2022/05/12 14:57:53