generator -> 生產者 yield -> 產出javascript
generator 函數是 ES6 提供的一種異步編程解決方案vue
執行 generator 函數返回的是一個遍歷器對象
, 也就是說, 咱們可使用 next
方法, 來遍歷 generator 函數內部的每個狀態java
既然 generator 函數內部具備多個狀態, 那麼總該有一個標識來決定函數在遍歷過程當中應該在哪裏停下來, 因此咱們須要 yield
編程
下面經過一個簡單實例, 詳細解釋 yield 的工做原理json
function* foo() {
yield 'hello'
console.log('come from second yield')
yield 'world'
return 'ending'
}
const g = foo()
// 執行過程
> g.next()
< { value: 'hello', done: false }
> g.next()
log: come from second yield
< { value: 'world', done: false }
> g.next()
< { value: 'ending', done: true }
> g.next()
< { value: undefined, done: true }
複製代碼
foo
函數會返回一個遍歷器對象
, 調用遍歷器對象的 next
方法, 使指針移向下一個狀態next
方法, 內部指針就從函數頭部上一次停下來的地方開始執行, 直到遇到下一條 yield 語句或 return 爲止next
方法的返回對象:
next
方法, 都只會返回 { value: undefined, done: true }
從 generator 的行爲能夠看出, 實際上等同於 javascript 提供了一個手動 "惰性求值" 的語法功能api
注意事項:數組
console.log('hello' + (yiled 123))
generator 函數是能夠傳遞參數的, 但 generator 函數有兩種傳參的方式bash
generator 函數傳參跟普通函數傳參是同樣的, 一個參數能在 generator 函數的任何狀態中讀取到數據結構
function* foo(x) {
console.log(x)
yield 'step 1'
console.log(x)
yield 'step 2'
console.log(x)
return 'step 3'
}
const g = foo('hello world')
複製代碼
以上代碼片斷, 不管在函數體的哪個狀態, 都能讀取到參數 hello world
異步
next 方法傳遞參數, 就跟普通函數傳參徹底不同了
yield 語句自己沒有返回值, 或者說老是返回 undefined, next 方法能夠帶一個參數, 該參數會被當作該狀態以前全部 yield 語句的返回值
咱們先來看看下面的表達式
function* foo() {
const x = yield 10
console.log(x)
return 'ending'
}
const g = foo()
複製代碼
g.next() log: undefined < { value: 'ending', done: true }
<br>
若是咱們但願打印出來的 `x` 的值是 `hello world`, 就必須使用 next 方法傳遞參數
該參數會被當作上一條 yield 語句的返回值
``` javascript
> g.next()
< { value: 10, done: false }
> g.next('hello world')
log: hello world
< { value: 'ending', done: true }
複製代碼
function* foo(x) {
let y = 2 * (yield (x + 5))
let z = yield y / 4 + 3
return (x + y - z)
}
const g = foo(10)
複製代碼
g.next() // 1
g.next(4) // 2
g.next(8) // 3
複製代碼
運算過程:
1.
x = 10
yield (10 + 5) => 15
> { value: 15, done: false }
2.
y = 2 * 4 => 8
yield (8 / 4 + 3) => 5
> {value: 5, done: false}
3.
x = 10
y = 8 // 保留了上一次 next 方法執行後的值
z = 8
return (10 + 8 - 8) => 10
> { value: 10, done: true }
複製代碼
done = true
function* foo() {
try {
yield console.log(variate)
yield console.log('hello world')
} catch(err) {
console.log(err)
}
}
const g = foo()
g.next()
> ReferenceError: variate is not defined
at foo (index.js:3)
at foo.next (<anonymous>)
at <anonymous>:1:3
> { value: undefined, done: true }
複製代碼
若是在內部 catch
片斷中將錯誤使用全局方法 throw
拋出, 該錯誤依然可以被外部 try...catch
所捕獲:
function* foo() {
try {
yield console.log(variate)
yield console.log('hello world')
} catch(err) {
throw err
}
}
const g = foo()
try {
g.next()
} catch(err) {
console.log('外部捕獲', err)
}
> 外部捕獲 ReferenceError: variate is not defined
at foo (index.js:3)
at foo.next (<anonymous>) at index.js:13 複製代碼
由於 generator 函數執行後返回的是一個遍歷器對象, 因此咱們可使用 for...of
循環來遍歷它
function* foo() {
yield 1
yield 2
yield 3
return 'ending'
}
const g = foo()
for (let v of g) {
console.log(v)
}
// < 1
// < 2
// < 3
複製代碼
for...of
循環, 不須要使用 next
語句done
屬性爲 true
, for...of
循環就會終止for...of
循環終止後不會返回 對象屬性 done
爲 true
的值, 因此上面的例子沒有返回 return 裏的 ending 值該語句用於在 generator 函數內部調用另外一個 generator 函數
function* bar() {
yield 3
yield 4
}
function* foo() {
yield 1
yield 2
yield* bar()
yield 5
return 'ending'
}
for (let v of foo()) {
console.log(v)
}
// < 1 2 3 4 5
複製代碼
for...of
的語法糖for...of
替代yield* bar()
# 徹底等價於:
for (let v of bar()) {
yield v
}
複製代碼
function* gen() {
yield* [1, 2, 3]
yield* 'abc'
}
for (let v of gen()) {
console.log(v)
}
// < 1 2 3 a b c
複製代碼
Iterator
接口的數據結構, 都可以被 yield*
遍歷和 yield
不一樣的是(yield 自己沒有返回值, 必須由 next 方法賦予), 若是當被 yield*
代理的 generator 函數有 return 語句時, return 返回的值能夠被永久保存
function* foo() {
yield 2
return 'hello yield*'
}
function* gen() {
const a = yield 1
console.log(a) // -> undefined
const b = yield* foo()
console.log(b) // -> hello yield*
yield 2
console.log(b) // -> hello yield*
yield 3
}
const g = gen()
複製代碼
const tree = [1, 2, [3, 4, [5, 6, [7, 8, 9]]], 10, 11]
function* loopTree(tree) {
if (Array.isArray(tree)) {
for (let i = 0; i < tree.length; i ++) {
yield* loopTree(tree[i])
}
} else {
yield tree
}
}
for (let v of loopTree(tree)) {
console.log(v)
}
複製代碼
loopTree
, 該函數接收一個數組, 或是數字做爲參數yield*
調用自身/** * 普通 xhr 請求封裝 * @param {String} url 請求地址 * @return {void} void */
function call(url) {
const xhr = new XMLHttpRequest()
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304) {
const res = JSON.parse(xhr.responseText)
// 3. 請求成功, 將請求結果賦值給 result 變量, 並進入下一個狀態
g.next(res)
} else {
console.log(`error: ${xhr.status}`)
}
}
}
xhr.open('get', url, true)
xhr.send(null)
}
function* fetchData() {
// 2. 發送 xhr 請求
const result = yield call('https://www.vue-js.com/api/v1/topics')
// 4. 打印出請求結果
console.log(result)
}
const g = fetchData()
// 1. 開始遍歷 generator 函數
g.next()
複製代碼
const obj = {
name: '木子七',
age: '25',
city: '重慶'
}
/** * 部署 Iterator 接口 * @param {Object} obj 對象 * @yield {Array} 將對象屬性轉換爲數組 */
function* iterEntires(obj) {
let keys = Object.keys(obj)
for (let i = 0; i < keys.length; i ++) {
let key = keys[i]
yield [key, obj[key]]
}
}
for (let [key, value] of iterEntires(obj)) {
console.log(key, value)
}
< name 木子七
< age 25
< city 重慶
複製代碼
generator 與 Promise 結合後, 實際上就是 async/await
的封裝實現, 下面小結會詳細描述 async/await
原理
// 1. 定義 generator 函數
// - 其返回的原生 fetch 方法是個 Promise 對象
function* fetchTopics() {
yield fetch('https://www.vue-js.com/api/v1/topics')
}
const g = fetchTopics()
// 2. 調用 next 方法
const result = g.next()
// 3. g.next() 返回的 { value: ..., done } 中的 value 就是 Promise 對象
result.value
.then(res => res.json())
.then(res => console.log(res))
複製代碼
封裝的方法實現
/** * 封裝用來執行 generator 函數的方法 * @param {Func} generator generator 函數 */
function fork(generator) {
// 1. 傳入 generator 函數, 並執行返回一個遍歷器對象
const it = generator()
/** * 3. 遍歷 generator 函數中的全部 Promise 狀態 * go 函數會不停的使用 next 方法調用自身, 直到全部狀態遍歷完成 * @param {Object} result 執行 next 方法後返回的數據 */
function go(result) {
if (result.done) return result.value
return result.value.then(
value => go(it.next(value)),
error => go(it.throw(error))
)
}
// 2. 初次執行 next 語句, 進入 go 函數邏輯
go(it.next())
}
/** * 普通的 Promise 請求方法 * @param {String} url 請求路徑 */
function call(url) {
return new Promise(resolve => {
fetch(url)
.then(res => res.json())
.then(res => resolve(res))
})
}
/** * 業務邏輯 generator 函數 * - 先請求 topics 獲取全部主題列表 * - 再經過 topics 返回的 id, 請求第一個主題的詳情 */
const fetchTopics = function* () {
try {
const topic = yield call('https://www.vue-js.com/api/v1/topics')
const id = topic.data[0].id
const detail = yield call(`https://www.vue-js.com/api/v1/topic/${id}`)
console.log(topic, detail)
} catch(error) {
console.log(error)
}
}
fork(fetchTopics)
複製代碼
async 函數屬於 ES7 的語法, 須要
Babel
或regenerator
轉碼後才能使用
async 函數就是 Generator 函數的語法糖, 其特色有:
Generator
函數的執行必須依靠執行器, 而 async
函數自帶執行器, 也就是說, async
函數的執行與普通函數同樣, 只要一行next
方法, 自動執行async
表示函數裏有異步操做, await
表示緊跟在後面的表達式須要等待結果await
命令後面必須是 Promise
對象, 若是是其餘原始類型的值, 其等同於同步操做function timeout() {
return new Promise(resolve => {
setTimeout(resolve, 2000)
})
}
async function go() {
await timeout().then(() => console.log(1))
console.log(2)
}
go()
// 執行輸出, 先輸出1 後輸出2
// -> 1
// -> 2
複製代碼
function timeout() {
return new Promise(resolve => {
setTimeout(resolve, 2000)
})
}
async function go() {
await timeout().then(() => console.log(1))
console.log(2)
}
go().then(() => console.log(3))
// -> 1
// -> 2
// -> 3
複製代碼
下面咱們使用 async 函數來實現以前的異步請求例子
const call = url => (
new Promise(resolve => {
fetch(url)
.then(res => res.json())
.then(res => resolve(res))
})
)
const fetchTopics = async function() {
const topic = await call('https://www.vue-js.com/api/v1/topics')
const id = topic.data[0].id
const detail = await call(`https://www.vue-js.com/api/v1/topic/${id}`)
console.log(topic, detail)
}
fetchTopics().then(() => console.log('request success!'))
複製代碼
總結: async 函數的實現比 Generator 函數簡潔了許多, 幾乎沒有語義不相關的代碼, 它將 Generator 寫法中的自動執行器改在了語言層面提供, 不暴露給用戶, 所以減小了許多代碼量