在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問答/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

請(qǐng)問為什么會(huì)輸出一個(gè) {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í)附帶了參數(shù)的話,generator會(huì)繼續(xù)執(zhí)行,直到下一個(gè)yield時(shí)停止,這是會(huì)把yield表達(dá)式換成傳入的參數(shù)。

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

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

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

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

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

2017年10月15日 13:28