鍍金池/ 問答/HTML/ ES6 generator的yield問題

ES6 generator的yield問題

function* dataConsumer() {
    console.log('Started');
    console.log(`1. ${yield}`);
    console.log(`2. ${yield}`);
    return 'result';
}

let genObj = dataConsumer();
console.log(genObj.next());// Started

genObj.next('a');// 1. a

// genObj.next('b');//2. b

上述代碼輸出結(jié)果為

Started
{value: undefined, done: false}
1. a
2. b

請問為什么會輸出一個 {value: undefined, done: false},
而第二次執(zhí)行yield則沒有返回{value,done}的型式

回答
編輯回答
情皺
Calling the next() method with an argument will resume the generator function execution, replacing the yield expression where execution was paused with the argument from next().
from: https://developer.mozilla.org...

就是說,如果你調(diào)用next方法時附帶了參數(shù)的話,generator會繼續(xù)執(zhí)行,直到下一個yield時停止,這是會把yield表達式換成傳入的參數(shù)。

2017年4月26日 00:51
編輯回答
醉淸風(fēng)

console.log(genObj.next());這個語句會讓dataConsumer在console.log(1. ${yield});這兒停止,而這里yield的返回值是undefined。也就說,實際上是console.log(1. ${yield undefined});所以genObj.next()得到的是{value:undefined,done:false},也就是console.log的輸出。而你后來傳a給next時沒有console.log,所以沒打印出來,加個log應(yīng)該也會打印這個undefined。
我是用手機回答的,可能排版有問題。我的理解是這樣的,有問題歡迎指出。

2018年8月16日 20:36
編輯回答
法克魷

Generatorh函數(shù)最大的特點就是可以交出函數(shù)的控制權(quán),通過yield實現(xiàn)。在Generator函數(shù)的執(zhí)行中遇到y(tǒng)ield命令就會停止執(zhí)行,并且把yield命令后面表達式的計算值傳遞到外面。
當(dāng)想要再次執(zhí)行Generator函數(shù)時,需要使用首次執(zhí)行Generator函數(shù)時返回的迭代器調(diào)用next方法實現(xiàn)。這里,有一個點需要注意,也就是,首次調(diào)用Generator函數(shù)時并不會執(zhí)行函數(shù)內(nèi)部的邏輯,而是返回一個迭代器,當(dāng)調(diào)用next方法時,才會開始執(zhí)行內(nèi)部的邏輯。
在調(diào)用next方法時,可以向Generator函數(shù)內(nèi)部傳入數(shù)據(jù),通過yeild命令的返回值傳遞,類似這樣:
var fromOuter = yeild 'to outer'
這樣例子中執(zhí)行到第一個yield命令時,內(nèi)部交出控制權(quán),停止執(zhí)行,因為沒有返回值,所以輸出結(jié)果中的value是undefined,當(dāng)再次調(diào)用next方法時,傳入的字符串'a'被yeild返回,輸出 1、a。

如果還有什么不懂的可以參考阮一峰的es入門中對Generator函數(shù)的講解。generator

2017年10月15日 13:28