ES6 中生成器(Generator)的应用场景是什么?

互联网冲浪金牌选手 2023-10-04 09:45:10 浏览数 (745)
反馈

ES6 中生成器(Generator)的典型应用场景有什么?

  1. 异步编程

Generator可以暂停函数执行,yield表达式可以向外返回内部状态。这使得它很适合代表异步流程。比如发送一个异步请求:

function* fetch() {
  const data = yield fetchAsync();
  console.log(data);
}


const g = fetch();
g.next(); // 发送异步请求
g.next(response); // 收到响应,继续执行

  1. 流处理

Generator可以 Yield 输入和输出,适合代表流处理步骤。

function* fib() {
  let a = 0;
  let b = 1;
  while (true) {
    yield a;
    [a, b] = [b, a + b]; 
  }
}


const sequence = fib();
sequence.next(); // {value: 0, done: false}
sequence.next(); // {value: 1, done: false}
sequence.next(); // {value: 1, done: false}
// ...

  1. 状态机

Generator可以维护状态,每次调用 next 方法都可以保持上次调用的状态,适合实现状态机。

const state = function* () {
  while(true) {
    yield 'A';
    // ...
    yield 'B';
  }
}


const status = state();
status.next(); // {value: 'A', done: false}
status.next(); // {value: 'B', done: false}

  1. 并发

Generator函数可以暂停执行,用于控制并发 númer。

function* limit(count) {
  let i = 0;
  while (i < count) {
    yield i++;
  }
}


const limiter = limit(3);


function task(name) {
  console.log(name);
}


limiter.next().value.then(task); // task 1 
limiter.next().value.then(task); // task 2
limiter.next().value.then(task); // task 3

所以总结Generator的应用场景,最典型的是代表异步流程和状态机。

想学习原理和语法, 请看最通俗易懂的 ES6 Generator(生成器)教程

0 人点赞