溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

ES6中Generator與異步操作的示例分析

發(fā)布時(shí)間:2021-08-19 11:00:53 來源:億速云 閱讀:125 作者:小新 欄目:web開發(fā)

這篇文章主要為大家展示了“ES6中Generator與異步操作的示例分析”,內(nèi)容簡(jiǎn)而易懂,條理清晰,希望能夠幫助大家解決疑惑,下面讓小編帶領(lǐng)大家一起研究并學(xué)習(xí)一下“ES6中Generator與異步操作的示例分析”這篇文章吧。

Generator與異步操作

1.Generator概念

可以把Generator理解成一個(gè)狀態(tài)機(jī)(好像React中有很多state),封裝了多個(gè)內(nèi)部狀態(tài)。執(zhí)行Generator返回的是一個(gè)遍歷器對(duì)象,可以遍歷Generator產(chǎn)生的每一個(gè)狀態(tài)。在function后加*就可以聲明一個(gè)Generator函數(shù)。

function* hiGenerator(){
yield 'hi';
yield 'ES5';
return '!';
}
var hi = hiGenerator();
console.log(hi); //hiGenerator {[[GeneratorStatus]]: "suspended", [[GeneratorReceiver]]: Window}
console.log(hi.next()); //Object {value: "hi", done: false}
console.log(hi.next()); //Object {value: "ES5", done: false}
console.log(hi.next()); //Object {value: "!", done: true}

2.yield語(yǔ)句

由于Generator函數(shù)返回的遍歷器對(duì)象,只有調(diào)用next()方法才會(huì)遍歷到下一個(gè)狀態(tài),所以其實(shí)提供了一種可以暫停的執(zhí)行函數(shù)。每次執(zhí)行next(),遇到y(tǒng)ield語(yǔ)句就暫停執(zhí)行,且將yield后的表達(dá)式的值作為返回的對(duì)象的value值;如果沒有遇到y(tǒng)ield,則返回return語(yǔ)句作為返回對(duì)象的value值;如果沒有return,則返回對(duì)象的value值為undefined。

3.next方法

next()方法可以帶一個(gè)參數(shù),該參數(shù)會(huì)被當(dāng)做上一條yield語(yǔ)句的返回值。

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

如果不給next()傳參,會(huì)使得下一步計(jì)算無(wú)法進(jìn)行。

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); //add {[[GeneratorStatus]]: "suspended", [[GeneratorReceiver]]: Window}
console.log(sum.next()); //Object {value: 1, done: false}
console.log(sum.next(1)); //Object {value: 4, done: false}
console.log(sum.next(3)); //Object {value: undefined, done: true}

4.用for..of...遍歷Generator

用for..of...遍歷Generator時(shí)候,不需要顯示調(diào)用next()方法。

5.一個(gè)Generator函數(shù)產(chǎn)生的遍歷器對(duì)象g調(diào)用return方法后,返回對(duì)象的value屬性為return方法的參數(shù)。

6.在一個(gè)Generator函數(shù)內(nèi)部調(diào)用另一個(gè)Generator函數(shù)。需要使用yield*。

以上是“ES6中Generator與異步操作的示例分析”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對(duì)大家有所幫助,如果還想學(xué)習(xí)更多知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI