DIV CSS 佈局教程網

ES6 Generator 與非同步流程實戰解析
編輯:JavaScript技巧     

本文以實例為主線,梳理 ES6 中 Generator 的運作方式,以及它如何被拿來編排非同步任務。

一、Generator 是什麼

把 Generator 想成一台狀態機就好懂了:函數體被切成好幾段,段與段之間用 yield 標記斷點。呼叫 Generator 函數並不會立刻執行任何程式碼,你拿到的是一個遍歷器物件,靠反覆呼叫 next() 把狀態往前推進。

宣告方式很簡單,在 function 後面補上一個星號即可。

function* hiGenerator(){
  yield 'hi';
  yield 'ES5';
  return '!';
}
var hi = hiGenerator();
console.log(hi);        // 此時函數體尚未執行,狀態為 suspended
console.log(hi.next()); // {value: "hi", done: false}
console.log(hi.next()); // {value: "ES5", done: false}
console.log(hi.next()); // {value: "!", done: true}

二、yield 語句:可暫停的執行點

因為必須呼叫 next() 才會推進到下一個狀態,Generator 等於自帶了一種「可暫停執行」的能力。每次 next() 遇到 yield 就停下,並把 yield 後面表達式的值當作這次回傳物件的 value;若一路沒碰到 yield,則以 return 的值作為 value;連 return 都沒有,value 就是 undefined。

三、next 方法可以帶參數

next() 接受一個參數,這個參數會成為上一條 yield 語句的回傳值,也就是說它能「往回」把資料送回函數體內。

function* add(c, d){
  var a = 0;
  a = yield a + c;
  a = yield a + d;
  return;
}
var sum = add(1, 2);
console.log(sum.next()); // {value: 1, done: false}
console.log(sum.next()); // {value: NaN, done: false}
console.log(sum.next()); // {value: undefined, done: true}

如果呼叫 next() 時不傳參,等於把 undefined 塞回上一個 yield,後續計算自然無法完成。

function* add(c, d){
  var a = 0;
  a = yield a + c;
  a = yield a + d + 1;
  return;
}
var sum = add(1, 2);
console.log(sum.next());    // {value: 1, done: false}
console.log(sum.next(1));   // {value: 4, done: false}
console.log(sum.next(3));   // {value: undefined, done: true}

四、幾個實用上要知道的細節

  • 用 for...of 遍歷 Generator 時,不需要手動呼叫 next()。
  • 對遍歷器物件呼叫 return 方法後,回傳物件的 value 就是 return 傳入的參數。
  • 想在 Generator 內部再呼叫另一個 Generator,必須寫成 yield*,如此才會把內層的 yield 值逐個往外傳。

掌握 yield 的暫停與 next() 的雙向傳值之後,再去看 co、async/await 這類非同步方案,會發現它們背後的思路其實一脉相承。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved