欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

ES6中Generator與異步操作實(shí)例分析

 更新時間:2017年03月31日 11:40:47   作者:柒青衿  
這篇文章主要介紹了ES6中Generator與異步操作,結(jié)合實(shí)例形式分析Generator的概念、功能及相關(guān)操作技巧,需要的朋友可以參考下

本文實(shí)例講述了ES6中Generator與異步操作。分享給大家供大家參考,具體如下:

Generator與異步操作

1.Generator概念

可以把Generator理解成一個狀態(tài)機(jī)(好像React中有很多state),封裝了多個內(nèi)部狀態(tài)。執(zhí)行Generator返回的是一個遍歷器對象,可以遍歷Generator產(chǎn)生的每一個狀態(tài)。在function后加*就可以聲明一個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語句

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

3.next方法

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

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()傳參,會使得下一步計(jì)算無法進(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時候,不需要顯示調(diào)用next()方法。

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

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

希望本文所述對大家ECMAScript程序設(shè)計(jì)有所幫助。

相關(guān)文章

最新評論