目录

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

# 如何可以解决这种问题?

将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
虽然因为awaitfor-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

# 最终的解决方式 —— 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
上次更新: 2022/05/12 14:57:53
最近更新
01
关于我
07-14
02
科学上网
11-15
03
OSS+CDN
09-23
更多文章>
极昼青春
买辣椒也用券