ES6 -- 异步编程神器2:Generator

xiaoxiao2021-02-28  122

Generator是ES6提供的一种全新的异步编程方案,它的基本语法如下:

function* myFirstBasicGenerator() { yield 'hello'; yield 'world'; return 'ending'; } var mfb = myFirstBasicGenerator();

我们可以注意到几点特别之处:

1、使用function*来声明函数; 2、函数体内使用yield表达式,并且在最后一步使用return。

在Generator函数中,yield其实是函数运行的分割线,也就是说,Generator函数在执行的过程中可以暂停;Generator函数真正执行的时候,是采用.next方法分步执行的:

mfb.next() // { value: 'hello', done: false } 这个对象是调用next的返回值 // other code ... 此时,Generator函数处于暂停的状态 mfb.next() // { value: 'world', done: false } mfb.next() // { value: 'ending', done: true } 到这里,其实已经执行完毕 mfb.next() // { value: undefined, done: true }

规则是,每次执行next方法后,函数就执行到yield然后停止,直到我们再次调用next方法,才会继续执行。

总结一下,调用 Generator 函数,返回一个遍历器对象,代表 Generator 函数的内部指针。以后,每次调用遍历器对象的next方法,就会返回一个有着value和done两个属性的对象。value属性表示当前的内部状态的值,是yield表达式后面那个表达式的值;done属性是一个布尔值,表示是否遍历结束。

由于Generator函数中可以存在多个yield,那么这个函数相当于是可以有很多个返回值,每次我们调用next,就会得到一组返回值。也就是,Generator 函数可以返回一系列的值,因为可以有任意多个yield,这也就是它的名称的来历(英语中,generator 这个词是“生成器”的意思)。

另外,Generator函数还有一个延缓执行的作用:

function* g() { console.log('执行...') } var generator = g();// 不同于普通函数,此时函数并没有执行 setTimeout(function () { generator.next()// 此时我们才能在控制台看到“执行...”的字样 }, 2000);

更多内容,可以参见大神博客:http://es6.ruanyifeng.com/#docs/generator

转载请注明原文地址: https://www.6miu.com/read-29424.html

最新回复(0)