JS中的生成器知多少

什么是生成器

  • 生成器是ES6中新增的一种函数控制、使用的方案,它可以让我们更加灵活的控制函数什么时候继续执行、暂停执行等;* 平时我们会编写很多的函数,这些函数终止的条件通常是返回值或者发生了异常;* 生成器函数也是一个函数,但是和普通的函数有一些区别:1.首先,生成器函数需要在function的后面加一个符号:*;2.其次,生成器函数可以通过yield关键字来控制函数的执行流程;3.最后,生成器函数的返回值是一个Generator(生成器)

生成器其实是一种特殊的迭代器;

MDN: Instead, they return a special type of iterator, called a Generator.

生成器函数执行

生成器函数被调用后,它的函数体并不会立刻被执行,而是返回一个生成器对象;

而生成器其实是一种特殊的迭代器,因此它有next方法,并且会返回一个{done: true/false, value: xxx/undefined}这样的对象,当next()方法被首次(后续)调用时,它开始执行生成器函数中代码到首次(后续)出现yield的位置为止;

我们可以通过yield语句来返回结果作为value,yield语句后面可以写一个表达式或者一个值;

function* bar() {console.log("bar start");console.log("bar chunk1");yield;console.log("bar chunk2");yield;console.log("bar chunk3");yield;console.log("bar end");
}
const barResult = bar();
barResult.next();
// bar start
// bar chunk1
barResult.next();
// bar chunk2
barResult.next();
// bar chunk3
barResult.next();
// bar end
barResult.next(); 
function* bar() {console.log("bar start");console.log("bar chunk1");yield "result1";console.log("bar chunk2");yield "result2";console.log("bar chunk3");yield "result3";console.log("bar end");
}
const barResult = bar();
console.log(barResult.next()); // { value: 'result1', done: false }
console.log(barResult.next()); // { value: 'result2', done: false }
console.log(barResult.next()); // { value: 'result3', done: false }
console.log(barResult.next()); // { value: undefined, done: true } 

生成器传递参数-next函数

函数既然可以暂停来分段执行,那么函数应该是可以传递参数的,我们是否可以给每个分段来传递参数呢?

  • 答案是可以的 ;
  • 我们在调用next函数的时候,可以给它传递参数,这个参数会作为上一个yield语句的返回值;
  • 注意:也就是说我们是为本次的函数代码块执行提供了一个值;
function* foo(initial) {console.log("foo start");const value1 = yield initial + "aaa";const value2 = yield value1 + "bbb";const value3 = yield value2 + "ccc";
}

const generator = foo("sss");
const result1 = generator.next();
console.log("result1:", result1);
// foo start
// result1: { value: 'sssaaa', done: false }
const result2 = generator.next(result1.value);
console.log("result2:", result2);
// result2: { value: 'sssaaabbb', done: false }
const result3 = generator.next(result2.value);
console.log("result3:", result3);
// result3: { value: 'sssaaabbbccc', done: false } 

生成器提前结束-return函数

还有一个可以给生成器函数传递参数的方法是通过return函数;

return传值后这个生成器函数就会结束,之后调用next不会继续生成值了;

function* bar() {const value1 = yield "lzh";console.log("value1:", value1);const value2 = yield value1;const value3 = yield value2;
}

const generator = bar();
console.log(generator.next());
// { value: 'lzh', done: false }

// 第二段代码的执行, 使用了return
// 那么就意味着相当于在第一段代码的后面加上return, 就会提前终端生成器函数代码继续执行
console.log(generator.return(123));
// { value: 123, done: true }
console.log(generator.next());
// { value: undefined, done: true } 

生成器抛出异常-throw函数

除了给生成器函数内部传递参数之外,也可以给生成器函数内部抛出异常:

  • 抛出异常后我们可以在生成器函数中捕获异常;
  • 但是在catch语句中不能继续yield新的值了,但是可以在catch语句外使用yield继续中断函数的执行;
function* foo() {console.log("代码开始执行~");const value1 = 100;try {yield value1;} catch (error) {console.log("捕获到异常情况:", error);yield "abc";}console.log("第二段代码继续执行");const value2 = 200;yield value2;console.log("代码执行结束~");
}

const generator = foo();

const result = generator.next();
console.log(result);
//{ value: 100, done: false }
generator.throw("error message");
// 捕获到异常情况: error message
console.log(generator.next());
// 第二段代码继续执行
// { value: 200, done: false } 

生成器替代迭代器

既然生成器是一种特殊的迭代器,那么在某些情况下我们可以使用生成器来替代迭代器:

// 不使用生成器来实现
function createArrayIterator(array) {let index = 0;return {next() {if (index < array.length) {return { done: false, value: array[index++] };} else {return { done: true, value: undefined };}},};
}
const names = ["wws", "cck", "hsq"];
const namesIterator = createArrayIterator(names);
console.log(namesIterator.next());
console.log(namesIterator.next());
console.log(namesIterator.next());
console.log(namesIterator.next()); 
// 使用生成器来实现
function* createArrayIterator(array) {// for (const index in array) {// yield array[index];// }yield* array; // 相当于上面语句的操作
} 

注意到上面我们使用了yield* array这种写法,它用于委托给另一个generator或者可迭代对象。

自定义类迭代-生成器实现

// ClassRoom案例
class ClassRoom {constructor(address, name) {this.address = address;this.name = name;this.students = [];}entry(...students) {this.students.push(...students);}// [Symbol.iterator]() {// let index = 0;// return {// next: () => {// if (index < this.students.length) {// return { done: false, value: this.students[index++] };// } else {// return { done: true, value: undefined };// }// },// };// }[Symbol.iterator] = function* () {
 // for (const index in array) {// yield array[index];// }yield* array;};
}

const classroom = new ClassRoom("广州天河", "js高级课程");
classroom.entry("lzh", "coder1", "coder2");
for (const student of classroom) {console.log(student);
} 

对生成器的操作

既然生成器是一个迭代器,那么也就意味着迭代器支持的操作它都支持:

  • for…of语法;
  • Promise.all/allSettled/race/any方法调用;
  • 展开语法;
  • 解构赋值;
  • Set/Map构造函数调用…

异步代码的处理方案

目前为止,我们已经学习了Promise,生成器,迭代器了,那么,让我们来看一下异步代码的最终处理方案;

案例

假设我们需要向服务器发送网络请求来获取数据,一共需要发送三次请求,并且第二次请求的URL依赖于第一次的结果,第三次请求的URL依赖于第二次的结果。

function requestData(url) {return new Promise((resolve, reject) => {setTimeout(() => {resolve(url);});}, 1000);
} 

方案一:通过多次回调

requestData("aaa").then((value) => {requestData(`${value}bbb`).then((value) => {requestData(`${value}ccc`).then((value) => {console.log("finally result:", value);});});
});
// finally result: aaabbbccc 

采用回调函数的方式会造成回调地狱

方案二:使用promise对象的then方法返回值

requestData("aaa").then((value) => requestData(`${value}bbb`)).then((value) => requestData(`${value}ccc`)).then((value) => {console.log("finally result:", value);}); 

这种方法虽然解决了回调地狱,但是代码的可读性比较低

方案三:使用Promise加generator

function* getData(url) {const value1 = yield requestData(url);const value2 = yield requestData(`${value1}bbb`);const value3 = yield requestData(`${value2}ccc`);console.log("finally result:", value3);
}
// 3.1执行代码的方案:每次都手动执行
// const generator = getData("aaa");
// generator.next().value.then((value) => {
// generator.next(value).value.then((value) =>
// generator.next(value).value.then((value) => {
// return generator.next(value).value;
// })
// );
// });
// 3.2封装一个函数来执行生成器函数
function execGenerator(generatorFn, arg) {const generator = generatorFn(arg);function _exec(generator, arg) {const result = generator.next(arg);if (result.done) {return result.value;} else {result.value.then((value) => {_exec(generator, value);});}}_exec(generator);
}
// execGenerator(getData, "aaa");
// 3.3使用第三方库:co
const co = require("co");
co(getData, "aaa"); 

我们通过Promise+generator封装了一个包含我们请求逻辑的生成器函数,并编写了一个工具函数来执行这样的生成器函数(也可以使用第三方库co);

方案四:使用async/await

在ES8中新增的async和await能够很好地帮助我们编写执行这样类似于方案三中的代码:

async function getData(url) {const value1 = await requestData(url);const value2 = await requestData(`${value1}bbb`);const value3 = await requestData(`${value2}ccc`);console.log("finally result:", value3);
}
getData("aaa"); 

async/await的目的为了简化使用基于 promise 的 API 时所需的语法。async/await的行为就好像搭配使用了生成器和 promise。

最后

整理了75个JS高频面试题,并给出了答案和解析,基本上可以保证你能应付面试官关于JS的提问。



有需要的小伙伴,可以点击下方卡片领取,无偿分享

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值