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ù)。
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。
我是用手機回答的,可能排版有問題。我的理解是這樣的,有問題歡迎指出。
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
北大青鳥APTECH成立于1999年。依托北京大學(xué)優(yōu)質(zhì)雄厚的教育資源和背景,秉承“教育改變生活”的發(fā)展理念,致力于培養(yǎng)中國IT技能型緊缺人才,是大數(shù)據(jù)專業(yè)的國家
北大青鳥中博軟件學(xué)院創(chuàng)立于2003年,作為華東區(qū)著名互聯(lián)網(wǎng)學(xué)院和江蘇省首批服務(wù)外包人才培訓(xùn)基地,中博成功培育了近30000名軟件工程師走向高薪崗位,合作企業(yè)超4
中公教育集團創(chuàng)建于1999年,經(jīng)過二十年潛心發(fā)展,已由一家北大畢業(yè)生自主創(chuàng)業(yè)的信息技術(shù)與教育服務(wù)機構(gòu),發(fā)展為教育服務(wù)業(yè)的綜合性企業(yè)集團,成為集合面授教學(xué)培訓(xùn)、網(wǎng)
達內(nèi)教育集團成立于2002年,是一家由留學(xué)海歸創(chuàng)辦的高端職業(yè)教育培訓(xùn)機構(gòu),是中國一站式人才培養(yǎng)平臺、一站式人才輸送平臺。2014年4月3日在美國成功上市,融資1
浪潮集團項目經(jīng)理。精通Java與.NET 技術(shù), 熟練的跨平臺面向?qū)ο箝_發(fā)經(jīng)驗,技術(shù)功底深厚。 授課風(fēng)格 授課風(fēng)格清新自然、條理清晰、主次分明、重點難點突出、引人入勝。
曾工作于聯(lián)想擔(dān)任系統(tǒng)開發(fā)工程師,曾在博彥科技股份有限公司擔(dān)任項目經(jīng)理從事移動互聯(lián)網(wǎng)管理及研發(fā)工作,曾創(chuàng)辦藍懿科技有限責(zé)任公司從事總經(jīng)理職務(wù)負責(zé)iOS教學(xué)及管理工作。
精通HTML5和CSS3;Javascript及主流js庫,具有快速界面開發(fā)的能力,對瀏覽器兼容性、前端性能優(yōu)化等有深入理解。精通網(wǎng)頁制作和網(wǎng)頁游戲開發(fā)。
具有10 年的Java 企業(yè)應(yīng)用開發(fā)經(jīng)驗。曾經(jīng)歷任德國Software AG 技術(shù)顧問,美國Dachieve 系統(tǒng)架構(gòu)師,美國AngelEngineers Inc. 系統(tǒng)架構(gòu)師。