JavaScript 面试系列:如何理解 ES6 中 Gener

2022-10-19  本文已影响0人  you的日常
image.png

一、介绍

Generator 函数是 ES6 提供的一种异步编程解决方案,语法行为与传统函数完全不同

回顾下上文提到的解决异步的手段:

那么,上文我们提到 promsie 已经是一种比较流行的解决异步方案,那么为什么还出现 Generator?甚至 async/await 呢?

该问题我们留在后面再进行分析,下面先认识下 Generator

Generator函数

执行 Generator 函数会返回一个遍历器对象,可以依次遍历 Generator 函数内部的每一个状态

形式上,Generator 函数是一个普通函数,但是有两个特征:

function* helloWorldGenerator() {
  yield 'hello';
  yield 'world';
  return 'ending';
}

二、使用

Generator 函数会返回一个遍历器对象,即具有 Symbol.iterator 属性,并且返回给自己

function* gen(){
  // some code
}

var g = gen();

g[Symbol.iterator]() === g
// true

通过 yield 关键字可以暂停 generator 函数返回的遍历器对象的状态

function* helloWorldGenerator() {
  yield 'hello';
  yield 'world';
  return 'ending';
}
var hw = helloWorldGenerator();

上述存在三个状态:hello、world、return

通过 next 方法才会遍历到下一个内部状态,其运行逻辑如下:

上一篇 下一篇

猜你喜欢

热点阅读