ES6 yield 港控/mmm° 2021-06-24 14:36 383阅读 0赞 ## **一、介绍** ## yield 关键字用来暂停和继续一个生成器函数。我们可以在需要的时候控制函数的运行。 yield 关键字使生成器函数暂停执行,并返回跟在它后面的表达式的当前值。与return类似,但是可以使用next方法让生成器函数继续执行函数yield后面内容,直到遇到yield暂停或return返回或函数执行结束。 ## **二、使用** ## 函数返回对象包括value和done。其中value值是yield后面表达式值或return后面表达式值。done用于表示函数运行 function* ge() { //声明时需要添加*,普通函数内部不能使用yield关键字,否则会出错 yield '1'; yield '2'; yield '3'; return '4'; } var a = ge(); //调用函数后不会运行,而是返回指向函数内部状态的指针 a.next(); // { value: '1', done: false } 遇到yield暂停 a.next(); // { value: '2', done: false } a.next(); // { value: '3', done: false } a.next(); // { value: '4', done: true} 函数执行完毕,返回done a.next(); // { value: undefined, done: true} 已经执行完毕,返回undefined 如果next没有带有参数true,yield不能返回值,返回undefined;next函数带有参数true,即.next(true)时,那么yield就可以返回表达式的值,用于赋值。如果next带有其他参数,那么它就会将当前yield返回值置为该参数。如: var i = yield 1; // 将1赋值给i ## **三、for…of** ## for…of循环可以自动遍历Generator函数时生成的Iterator对象。 function* ge() { yield '1'; yield '2'; yield '3'; return '4'; } for(let v of ge()){ alert(V); // 1 2 3 4 } ## **四、yield与异步** ## 函数在遇到yield后暂停运行,我们可以在需要的地方使用next让它继续运行。并且必要时可以使用next传入参数。
还没有评论,来说两句吧...