异步迭代

1/17/2023

# 什么是异步迭代

异步迭代是指使用异步迭代器来迭代集合中的元素。异步迭代器是一种特殊的迭代器,可以在调用时暂停执行,并在需要时继续执行。它返回的是一个Promise对象,可以使用for...await...of语句或者手动迭代器来获取异步迭代器生成的值。

# 异步迭代的语法

异步迭代器使用async function*关键字定义,并使用yield语句返回生成的值。下面是一个简单的例子:

async function* myAsyncGenerator() {
  yield 'apple';
  yield 'banana';
  yield 'orange';
}
1
2
3
4
5

# 使用异步迭代器实现可迭代对象和迭代器

异步迭代器函数返回的是一个可迭代对象,可以直接使用for...await...of语句来遍历异步迭代器生成的值:

async function* myAsyncGenerator() {
  yield 'apple';
  yield 'banana';
  yield 'orange';
}

for await (let value of myAsyncGenerator()) {
  console.log(value);
}

// 输出:
// apple
// banana
// orange
1
2
3
4
5
6
7
8
9
10
11
12
13
14

也可以使用手动迭代器来遍历异步迭代器生成的值:

async function* myAsyncGenerator() {
  yield 'apple';
  yield 'banana';
  yield 'orange';
}

const myIterator = myAsyncGenerator();
console.log(await myIterator.next()); // { value: "apple", done: false }
console.log(await myIterator.next()); // { value: "banana", done: false }
console.log(await myIterator.next()); // { value: "orange", done: false }
console.log(await myIterator.next()); // { done: true }
1
2
3
4
5
6
7
8
9
10
11

# 异步迭代器的实现

异步迭代器的实现与同步迭代器的实现类似,只是在实现next()方法时,需要使用await关键字来等待异步操作完成。

class AsyncIterator {
  constructor(collection) {
    this.collection = collection;
    this.index = 0;
  }

  async next() {
    if (this.index < this.collection.length) {
      const value = this.collection[this.index];
      this.index++;
      return { value, done: false };
    } else {
      return { done: true };
    }
  }
}

class AsyncIterable {
  constructor(collection) {
    this.collection = collection;
  }

  async *[Symbol.asyncIterator]() {
    for (const item of this.collection) {
      yield item;
    }
  }
}

const collection = ['apple', 'banana', 'orange'];
const asyncIterable = new AsyncIterable(collection);
const asyncIterator = new AsyncIterator(collection);

(async () => {
  for await (const value of asyncIterable) {
    console.log(value);
  }

  console.log(await asyncIterator.next()); // { value: "apple", done: false }
  console.log(await asyncIterator.next()); // { value: "banana", done: false }
  console.log(await asyncIterator.next()); // { value: "orange", done: false }
  console.log(await asyncIterator.next()); // { done: true }
})();
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
36
37
38
39
40
41
42
43

# 异步迭代器的应用

异步迭代器可以用来实现异步的可迭代对象,比如异步的数组、异步的Map、异步的Set等。下面是一个异步的数组的例子:

class AsyncArray {
  constructor(array) {
    this.array = array;
  }

  async *[Symbol.asyncIterator]() {
    for (const item of this.array) {
      yield item;
    }
  }
}

const asyncArray = new AsyncArray(['apple', 'banana', 'orange']);

(async () => {
  for await (const value of asyncArray) {
    console.log(value);
  }
})();
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

# 异步迭代器的兼容性

异步迭代器的兼容性如下:

浏览器 Chrome Edge Firefox IE Opera Safari
支持情况 61+ 79+ 63+ 不支持 48+ 11.1+
编辑时间: 1/26/2023, 4:05:20 PM