 理解 GeneratorGenerator 是文掌握生 ES6 提供的一个新的数据类型,可以叫做 Generator 函数,成器但跟普通函数又有些不同。用G异步 其最大特点就是实现可以交出函数的执行权(即暂停执行): 定义时在 function 后面有一个*。可以使用关键字 yield 进行多次返回。编程调用后并不立即执行,文掌握生而是成器返回一个指向内部状态的指针对象,该对象是用G异步一个遍历器(Iterator)对象。调用返回遍历器对象的实现 next 方法,会移动内部指针,编程使得指针指向下一个状态。文掌握生会返回一个对象,成器表示当前阶段的用G异步信息。其中 value 属性是实现 yield 语句后面表达式的值,表示当前阶段的编程值;done 属性表示 Generator 函数是否执行完毕,即是否还有下一个阶段。返回遍历器对象有个 throw 方法可以抛出错误,抛出的错误可以被函数体内的b2b供应网 try/catch 代码块捕获。备注:yield 只能在 Generator 中使用,在其他地方使用会报错。 以下用一段代码作为示例说明: function* genDemo() { console.log(hello before) const hello = yield hello console.log(hello after, hello) yield world return end }运行结果如下:  执行 genDemo 这个 Generator 函数,返回的 g 是一个指针。这个时候没有任何打印,函数体内代码没有执行。执行 g.next() 运行到第一个 yield 处停止运行,返回 { value: ‘hello’, done: false }。value 值表示的是 yield 后面的运行结果,done 表示的是整个 Generator 是否执行完毕。继续执行 g.next(),到第二个 yield 处停止运行,后面还有代码,所以done 为false。继续执行 g.next(), 执行到 return 了,代码执行完毕,所以 done 为 true。继续执行 g.next(), 因为已经执行完毕了,继续执行的话,都会返回 { value: undefined, done: true }。注意:以上结果中,变量 hello 打印出来的值为 undefined。高防服务器说明没有被赋值。那么该怎么给赋值呢? 应该在执行 next 方法的时候传参来赋值。通过这种方法向 Generator 函数体内输入数据。 以下是运行示例:  第一次执行 g.next,运行到第一个 yield 处停止运行。这个时候 hello 变量还没有被赋值。第二次执行 g.next 时,传一个参数 ’wmm66’,会先将这个传入的参数赋值给上一次暂停时 yield 前面要赋值的变量,即上面代码中的 hello 变量。赋值完成后再往下运行代码,运行到下一个 yield 处。Generator 函数内部还可以部署错误处理代码,捕获函数体外抛出的错误。以下是示例代码和运行结果。 function* genDemo() { try { console.log(hello before) const hello = yield hello console.log(hello after, hello) yield world return end } catch(err) { console.warn(err) } }运行 g.throw 抛出错误。Generator 函数内部的 try/catch 就可以捕获到错误。发生错误后, Generator 函数就结束运行了,返回 { value: undefined, done: true }。 Generator 实现异步编程相对于异步,我们的思维更容易理解同步代码。异步编程的语法目标是网站模板让代码变得更像同步代码。 比如以下代码(这里假设逻辑上要求读取完 test1.txt,然后再读取 test2.txt)。 const fs = require(fs) fs.readFile(./test1.txt, function(err, data1) { if (err) return err console.log(data1.toString()) fs.readFile(./test2.txt, function(err, data2) { if (err) return err console.log(data2.toString()) }) })该代码是回调函数的方式。这种有先后顺序的时候,会出现多个函数嵌套,造成阅读和理解上的障碍。也就是常说的“回调地狱”。 我们把它改成 promise 的写法。 const fs = require(fs) const promiseReadFile = (file) => { return new Promise((resolve, reject) => { fs.readFile(file, function(err, data) { if (err) return reject(err) resolve(data) }) }) } promiseReadFile(./test1.txt) .then(data1 => { console.log(data1.toString()) }) .then(() => { return promiseReadFile(./test2.txt) }) .then(data2 => { console.log(data2.toString()) }).catch(err => { console.error(err) })这种链式调用的方式,逻辑上清晰了不少。 我们计划使用 Generator 函数,通过如下编码实现异步。 const genReadFile = function* (){ const data1 = yield readFile(./test1.txt) console.log(data1.toString()) const data2 = yield readFile(./test2.txt) console.log(data2.toString()) }Generator 函数和 yield 本身跟异步没有关系。yield 是对函数的执行流程进行变更,是控制函数执行流程用的,而恰好这个控制流程的机制能够简化回调函数和 promise 的调用。 我们现在要做的就是写一个方法,用来自动控制 Generator 函数的流程,接收和交还程序的执行权。 在这之前,先了解一下 thunk 函数。 thunk函数介绍最早的 thunk 函数起源于 “传值调用”和“传名调用”之争。 let x = 1 function fn(m) { return m * 2 } fn(x + 1)传值调用的主张:执行前就进行计算。先计算 x + 1 = 2,然后将值2传入fn 方法中:m * 2。传名调用的主张:只在执行的时候才进行计算。将 x + 1 直接传入到fn方法中:(x + 1) * 2。Javascript 是“传值调用”。在 JavaScript 语言中,Thunk 函数替换的不是表达式,而是多参数函数,将其替换成单参数的版本,且只接受回调函数作为参数。 // 正常版本的readFile const fn = fs.readFile(file, callback) // thunk版本的readFile function Thunk(file) { return function(callback) { return fn(file, callback) } } const thunkReadFile = Thunk(file) thunkReadFile(callback)该代码中的 thunkReadFile 函数,只接受回调函数作为参数。这个单参数版本,就叫做 Thunk 函数。 任何函数只要存在回调就可以 thunk 转换,下面是一个简单的 thunk 转换器。 const Thunk = function(fn) { return function() { const args = Array.prototype.slice.call(arguments) return function(callback) { args.push(callback) return fn.apply(this, args) } } }使用上面的转换器,生成 fs.readFile 的 Thunk 函数。 const readFileThunk = Thunk(fs.readFile) readFileThunk(file)(callback)有个插件 thunkify 可以直接转换。 const fs = require(fs) const thunkify = require(thunkify) const readFile = thunkify(fs.readFile) readFile(./test1.txt)(function(err, str) { // ... })实现回调函数的异步Thunk 函数现在可以用于 Generator 函数的自动流程管理。我们让 Generator 函数的 yield 后面都执行 Thunk 函数。就改造出了我们想要的代码。 const fs = require(fs) const thunkify = require(thunkify) const readFile = thunkify(fs.readFile) const genReadFile = function* (){ const data1 = yield readFile(./test1.txt) console.log(data1.toString()) const data2 = yield readFile(./test2.txt) console.log(data2.toString()) }那么应该怎么执行呢?我们先来分析一下: 第一次执行 next 方法,会返回对象中的 value 是一个函数,该函数可以传入一个callback,这个 callback 里面能够获取到 ./test1.txt 文件读出来的数据。读出来 ./test1.txt 文件的数据后,我们需要继续执行 next,此时需要传入从 ./test1.txt 文件读出来的数据,这样才能将该数据赋值给 Generator 函数中的 data1 变量。然后同上...所以执行方法如下: const g = genReadFile() const r1 = g.next() r1.value(function(err, data1){ if (err) throw err const r2 = g.next(data1) r2.value(function(err, data2){ if (err) throw err g.next(data2) }) })我们写一个 Generator 自动执行器,用来执行 Generator 函数。 function run(gen) { const g = gen() function next(err, data) { const result = g.next(data) if (result.done) return result.value(next) } next() } run(genReadFile)实现 Promise 的异步思路与回调函数相同,具体代码如下: const fs = require(fs) const readFile = (file) = >{ return new Promise((resolve, reject) = >{ fs.readFile(file, function(err, data) { if (err) return reject(err) resolve(data) }) }) } const genReadFile = function * () { const data1 = yield readFile(./test1.txt) console.log(data1.toString()) const data2 = yield readFile(./test2.txt) console.log(data2.toString()) }手动执行代码如下: const g = genReadFile() g.next().value.then(function(data1) { g.next(data1).value.then(function(data2) { g.next(data2) }) })Generator 自动执行器代码如下: function run(gen) { const g = gen() function next(data) { const { value, done } = g.next(data) if (done) return value value.then(function(data) { next(data) }) } next() } run(genReadFile)co函数有个成熟的函数库 co。该函数库接受 Generator 函数作为参数,返回一个 Promise 对象。 Thunk 函数示例: const fs = require(fs) const thunkify = require(thunkify) const co = require(co) const readFile = thunkify(fs.readFile) const genReadFile = function * () { const data1 = yield readFile(./test1.txt) console.log(data1.toString()) const data2 = yield readFile(./test2.txt) console.log(data2.toString()) } co(genReadFile) Promise 对象示例: const fs = require(fs) const co = require(co) const readFile = (file) = >{ return new Promise((resolve, reject) = >{ fs.readFile(file, function(err, data) { if (err) return reject(err) resolve(data) }) }) } const genReadFile = function * () { const data1 = yield readFile(./test1.txt) console.log(data1.toString()) const data2 = yield readFile(./test2.txt) console.log(data2.toString()) } co(genReadFile) Async/await 对比ES7 引入了 async 函数。一句话,async 函数就是 Generator 函数的语法糖。 Generator 函数封装的异步代码示例: const genReadFile = function* () { const data1 = yield readFile(./test1.txt) console.log(data1.toString()) const data2 = yield readFile(./test2.txt) console.log(data2.toString()) } co(genReadFile)改写成 async 函数写法: const asyncReadFile = async function() { const data1 = await readFile(./test1.txt) console.log(data1.toString()) const data2 = await readFile(./test2.txt) console.log(data2.toString()) } asyncReadFile()以上两段代码对比,async 函数就是将 Generator 函数的星号 * 替换成 async,放在 function 关键字前面,将 yield 替换成 await。 async 函数对 Generator 函数的改进,体现在以下几点: 内置执行器:Generator 函数的执行必须靠执行器(以上代码就是使用 co 模块执行),而 async 函数自带执行器。async 函数的执行,与普通函数一模一样。更好的语义:async 表示函数里有异步操作,await 表示紧跟在后面的表达式需要等待结果。语义更清晰。更广的适用性:co 模块约定,yield 命令后面只能是 Thunk 函数或 Promise 对象,而 async 函数的 await 命令后面,可以是Promise 对象和原始类型的值。返回值是 Promise:async 函数的返回值是 Promise 对象,这比 Generator 函数的返回值是 Iterator 。 对象方便多了。可以用 then 方法指定下一步的操作。 |