当前位置:网站首页>Generator Foundation

Generator Foundation

2022-07-06 07:33:00 Romantic bearded boy

One 、 Basic grammar

//* It means that there will be yield 
function*  Function name () {
    
    //  Function content 
    yield;
}

Two 、 call Generator function

Generator Functions are the same as ordinary functions , It's all through Function name () To make the call :

 Function name ();

however , Generator The function is called after , Does not execute internal code . But it will return an iterator object .

const it =  Function name ();
 next step , Calling iterator's  next()  Method to enter the function and execute the internal code of the function .

it.next();

3、 ... and 、yield

yield It can be used to block the execution of code in functions .

function* myGenerator() {
    
    console.log('1、myGenerator Yes ');
    yield;
    console.log('2、myGenerator Yes ');
}

const it = myGenerator();
it.next();
it.next();

yield It can be followed by an expression :

function* myGenerator() {
    
    console.log('1、myGenerator Yes ');
    yield 'hello';
    console.log('2、myGenerator Yes ');
    yield 'world';
    console.log('3、myGenerator Yes ');
}

const it = myGenerator();
console.log(it.next());
console.log(it.next());

next() You can also pass parameters , This parameter will be used as the current yield The return value of :

function* myGenerator() {
    
    console.log('1、myGenerator Yes ');
    const res = yield 'hello';
    console.log('res', res);
}

const it = myGenerator();
console.log(it.next());
console.log(it.next("world"));

Four 、 Deal with asynchronous

 Insert picture description here

原网站

版权声明
本文为[Romantic bearded boy]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202131916509195.html