App下載

ES6 中生成器(Generator)的應(yīng)用場(chǎng)景是什么?

互聯(lián)網(wǎng)沖浪金牌選手 2023-10-04 09:45:10 瀏覽數(shù) (971)
反饋

ES6 中生成器(Generator)的典型應(yīng)用場(chǎng)景有什么?

  1. 異步編程

Generator可以暫停函數(shù)執(zhí)行,yield表達(dá)式可以向外返回內(nèi)部狀態(tài)。這使得它很適合代表異步流程。比如發(fā)送一個(gè)異步請(qǐng)求:

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


const g = fetch();
g.next(); // 發(fā)送異步請(qǐng)求
g.next(response); // 收到響應(yīng),繼續(xù)執(zhí)行

  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. 狀態(tài)機(jī)

Generator可以維護(hù)狀態(tài),每次調(diào)用 next 方法都可以保持上次調(diào)用的狀態(tài),適合實(shí)現(xiàn)狀態(tài)機(jī)。

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. 并發(fā)

Generator函數(shù)可以暫停執(zhí)行,用于控制并發(fā) 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

所以總結(jié)Generator的應(yīng)用場(chǎng)景,最典型的是代表異步流程和狀態(tài)機(jī)。

想學(xué)習(xí)原理和語法, 請(qǐng)看最通俗易懂的 ES6 Generator(生成器)教程

0 人點(diǎn)贊