Home > Web Front-end > JS Tutorial > Detailed explanation of Generator_Basic knowledge in JavaScript ES6

Detailed explanation of Generator_Basic knowledge in JavaScript ES6

WBOY
Release: 2016-05-16 15:48:46
Original
1239 people have browsed it

I’m really excited about the new feature we’re discussing today because it’s the most amazing feature in ES6.

What does "magical" mean here? For beginners, this feature is completely different from previous JS, and even a little obscure. It's "magical" in the sense that it completely changes the normal behavior of the language.

Not only that, this feature can also simplify the program code and change the complex "callback stack" into a straight-line execution form.

Did I lay out too much? Let’s start with an in-depth introduction, and you can judge for yourself.
Introduction

What is a Generator?

Look at the code below:

function* quips(name) {
 yield "hello " + name + "!";
 yield "i hope you are enjoying the blog posts";
 if (name.startsWith("X")) {
  yield "it's cool how your name starts with X, " + name;
 }
 yield "see you later!";
}
 
function* quips(name) {
 yield "hello " + name + "!";
 yield "i hope you are enjoying the blog posts";
 if (name.startsWith("X")) {
  yield "it's cool how your name starts with X, " + name;
 }
 yield "see you later!";
}

Copy after login

The above code is a part of imitating Talking cat (a very popular application at the moment), Click here to try it, if you are confused about the code, then come back here See explanation below.

This looks a lot like a function, which is called a Generator function. It has a lot in common with our common functions, but you can also see the following two differences:

Normal functions start with function, but Generator functions start with function*.
Within the Generator function, yield is a keyword, somewhat similar to return. The difference is that all functions (including Generator functions) can only return once, while in Generator functions you can yield any number of times. The yield expression pauses the execution of the Generator function, and execution can then be resumed from where it was paused.

Common functions cannot pause execution, but Generator functions can. This is the biggest difference between the two.
Principle

What happens when quips() is called?

> var iter = quips("jorendorff");
 [object Generator]
> iter.next()
 { value: "hello jorendorff!", done: false }
> iter.next()
 { value: "i hope you are enjoying the blog posts", done: false }
> iter.next()
 { value: "see you later!", done: false }
> iter.next()
 { value: undefined, done: true }

 
> var iter = quips("jorendorff");
 [object Generator]
> iter.next()
 { value: "hello jorendorff!", done: false }
> iter.next()
 { value: "i hope you are enjoying the blog posts", done: false }
> iter.next()
 { value: "see you later!", done: false }
> iter.next()
 { value: undefined, done: true }

Copy after login

We are very familiar with the behavior of ordinary functions. When a function is called, it executes immediately until the function returns or throws an exception. This is second nature to all JS programmers.

The calling method of the Generator function is the same as the ordinary function: quips("jorendorff"), but when calling a Generator function, it is not executed immediately, but a Generator object (iter in the above code) is returned. At this time, the function Pause immediately on the first line of function code.

Every time the .next() method of a Generator object is called, the function begins executing until the next yield expression is encountered.

This is why we get a different string every time we call iter.next(), these are the values ​​produced by the yield expression inside the function.

When the last iter.next() is executed, the end of the Generator function is reached, so the .done property value of the returned result is true, and the .value property value is undefined.

Now, go back to the Talking cat DEMO and try adding some yield expressions to the code and see what happens.

Technically speaking, whenever the Generator function execution encounters a yield expression, the function's stack frame—local variables, function parameters, temporary values, and the current execution position are removed from the stack, but the Generator object remains The reference to the stack frame is removed, so the next time the .next() method is called, you can resume and continue execution.

It is worth reminding that Generator is not multi-threaded. In a language that supports multi-threading, multiple pieces of code can be executed at the same time, accompanied by competition for execution resources, uncertainty in execution results and better performance. This is not the case with Generator functions. When a Generator function is executed, it and its caller are executed in the same thread. Each execution sequence is determined and ordered, and the execution sequence will not change. Unlike threads, Generator functions can pause execution at internal yield markers.

By introducing the pause, execution and resumption of the Generator function, we know what the Generator function is, so now we raise a question: What is the use of the Generator function?
Iterator

Through the previous article, we know that iterator is not a built-in class of ES6, but is just an extension point of the language. You can define one by implementing the [Symbol.iterator]() and .next() methods. iterator.

However, implementing an interface still requires writing some code. Let’s take a look at how to implement an iterator in practice. Let’s take the implementation of a range iterator as an example. This iterator simply accumulates from one number to another. A number, a bit like the for (;;) loop in C language.

// This should "ding" three times
for (var value of range(0, 3)) {
 alert("Ding! at floor #" + value);
}
 
// This should "ding" three times
for (var value of range(0, 3)) {
 alert("Ding! at floor #" + value);
}
Copy after login

Now there is a solution, which is to use ES6 classes. (If you’re not familiar with class syntax yet, don’t worry, I’ll cover it in a future article.)

class RangeIterator {
 constructor(start, stop) {
  this.value = start;
  this.stop = stop;
 }

 [Symbol.iterator]() { return this; }

 next() {
  var value = this.value;
  if (value < this.stop) {
   this.value++;
   return {done: false, value: value};
  } else {
   return {done: true, value: undefined};
  }
 }
}

// Return a new iterator that counts up from 'start' to 'stop'.
function range(start, stop) {
 return new RangeIterator(start, stop);
}
 
class RangeIterator {
 constructor(start, stop) {
  this.value = start;
  this.stop = stop;
 }
 
 [Symbol.iterator]() { return this; }
 
 next() {
  var value = this.value;
  if (value < this.stop) {
   this.value++;
   return {done: false, value: value};
  } else {
   return {done: true, value: undefined};
  }
 }
}
 
// Return a new iterator that counts up from 'start' to 'stop'.
function range(start, stop) {
 return new RangeIterator(start, stop);
}

Copy after login

查看该 DEMO。

这种实现方式与 Java 和 Swift 的实现方式类似,看上去还不错,但还不能说上面代码就完全正确,代码没有任何 Bug?这很难说。我们看不到任何传统的 for (;;) 循环代码:迭代器的协议迫使我们将循环拆散了。

在这一点上,你也许会对迭代器不那么热衷了,它们使用起来很方便,但是实现起来似乎很难。

我们可以引入一种新的实现方式,以使得实现迭代器更加容易。上面介绍的 Generator 可以用在这里吗?我们来试试:

function* range(start, stop) {
 for (var i = start; i < stop; i++)
  yield i;
}
 
function* range(start, stop) {
 for (var i = start; i < stop; i++)
  yield i;
}
Copy after login

查看该 DEMO

上面这 4 行代码就可以完全替代之前的那个 23 行的实现,替换掉整个 RangeIterator 类,这是因为 Generator 天生就是迭代器,所有的 Generator 都原生实现了 .next() 和 [Symbol.iterator]() 方法。你只需要实现其中的循环逻辑就够了。

不使用 Generator 去实现一个迭代器就像被迫写一个很长很长的邮件一样,本来简单的表达出你的意思就可以了,RangeIterator 的实现是冗长和令人费解的,因为它没有使用循环语法去实现一个循环功能。使用 Generator 才是我们需要掌握的实现方式。

我们可以使用作为迭代器的 Generator 的哪些功能呢?

使任何对象可遍历 — 编写一个 Genetator 函数去遍历 this,每遍历到一个值就 yield 一下,然后将该 Generator 函数作为要遍历的对象上的 [Symbol.iterator] 方法的实现。
简化返回数组的函数 — 假如有一个每次调用时都返回一个数组的函数,比如:

// Divide the one-dimensional array 'icons'
// into arrays of length 'rowLength'.
function splitIntoRows(icons, rowLength) {
 var rows = [];
 for (var i = 0; i < icons.length; i += rowLength) {
  rows.push(icons.slice(i, i + rowLength));
 }
 return rows;
}

 
// Divide the one-dimensional array 'icons'
// into arrays of length 'rowLength'.
function splitIntoRows(icons, rowLength) {
 var rows = [];
 for (var i = 0; i < icons.length; i += rowLength) {
  rows.push(icons.slice(i, i + rowLength));
 }
 return rows;
}

Copy after login

使用 Generator 可以简化这类函数:

function* splitIntoRows(icons, rowLength) {
 for (var i = 0; i < icons.length; i += rowLength) {
  yield icons.slice(i, i + rowLength);
 }
}
 
function* splitIntoRows(icons, rowLength) {
 for (var i = 0; i < icons.length; i += rowLength) {
  yield icons.slice(i, i + rowLength);
 }
}
Copy after login

这两者唯一的区别在于,前者在调用时计算出了所有结果并用一个数组返回,后者返回的是一个迭代器,结果是在需要的时候才进行计算,然后一个一个地返回。

无穷大的结果集 — 我们不能构建一个无穷大的数组,但是我们可以返回一个生成无尽序列的 Generator,并且每个调用者都可以从中获取到任意多个需要的值。
重构复杂的循环 — 你是否想将一个复杂冗长的函数重构为两个简单的函数?Generator 是你重构工具箱中一把新的瑞士军刀。对于一个复杂的循环,我们可以将生成数据集那部分代码重构为一个 Generator 函数,然后用 for-of 遍历:for (var data of myNewGenerator(args))。
构建迭代器的工具 — ES6 并没有提供一个可扩展的库,来对数据集进行 filter 和 map等操作,但 Generator 可以用几行代码就实现这类功能。

例如,假设你需要在 Nodelist 上实现与 Array.prototype.filter 同样的功能的方法。小菜一碟的事:

function* filter(test, iterable) {
 for (var item of iterable) {
  if (test(item))
   yield item;
 }
}

 
function* filter(test, iterable) {
 for (var item of iterable) {
  if (test(item))
   yield item;
 }
}

Copy after login

所以,Generator 很实用吧?当然,这是实现自定义迭代器最简单直接的方式,并且,在 ES6 中,迭代器是数据集和循环的新标准。

但,这还不是 Generator 的全部功能。
异步代码

异步 API 通常都需要一个回调函数,这意味着每次你都需要编写一个匿名函数来处理异步结果。如果同时处理三个异步事务,我们看到的是三个缩进层次的代码,而不仅仅是三行代码。

看下面代码:

}).on('close', function () {
 done(undefined, undefined);
}).on('error', function (error) {
 done(error);
});
 
}).on('close', function () {
 done(undefined, undefined);
}).on('error', function (error) {
 done(error);
});
Copy after login

异步 API 通常都有错误处理的约定,不同的 API 有不同的约定。大多数情况下,错误是默认丢弃的,甚至有些将成功也默认丢弃了。

直到现在,这些问题仍是我们处理异步编程必须付出的代价,而且我们也已经接受了异步代码只是看不来不像同步代码那样简单和友好。

Generator 给我们带来了希望,我们可以不再采用上面的方式。

Q.async()是一个将 Generator 和 Promise 结合起来处理异步代码的实验性尝试,让我们的异步代码类似于相应的同步代码。

例如:

// Synchronous code to make some noise.
function makeNoise() {
 shake();
 rattle();
 roll();
}

// Asynchronous code to make some noise.
// Returns a Promise object that becomes resolved
// when we're done making noise.
function makeNoise_async() {
 return Q.async(function* () {
  yield shake_async();
  yield rattle_async();
  yield roll_async();
 });
}
 
// Synchronous code to make some noise.
function makeNoise() {
 shake();
 rattle();
 roll();
}
 
// Asynchronous code to make some noise.
// Returns a Promise object that becomes resolved
// when we're done making noise.
function makeNoise_async() {
 return Q.async(function* () {
  yield shake_async();
  yield rattle_async();
  yield roll_async();
 });
}

Copy after login

The biggest difference is that you need to add the yield keyword in front of each asynchronous method call.

In Q.async, adding an if statement or try-catch exception handling, just like in synchronous code, reduces a lot of learning costs compared to other ways of writing asynchronous code.

Generator provides us with an asynchronous programming model that is more suitable for the way the human brain thinks. But better syntax may be more helpful. In ES7, an asynchronous processing function based on Promise and Generator is being planned, inspired by similar features in C#.
Compatibility

On the server side, you can now use Generator directly in io.js (or start Node with the --harmony startup parameter in NodeJs).

On the browser side, currently only Firefox 27 and Chrome 39 or above support Generator. If you want to use it directly on the Web, you can use Babel or Google's Traceur to convert ES6 code into Web-friendly ES5 code.

Some digressions: The JS version of Generator was first implemented by Brendan Eich. He drew on the implementation of Python Generator, which was inspired by Icon. Firefox 2.0 absorbed Generator as early as 2006. But the road to standardization is bumpy. Along the way, its syntax and behavior have undergone many changes. The ES6 Generator in Firefox and Chrome was implemented by Andy Wingo, and this work was sponsored by Bloomberg.
yield;

There are some unmentioned parts about Generator. We have not yet covered the use of .throw() and .return() methods, the optional parameters of .next() method, and the yield* syntax. But I think this post is already long enough, and just like Generator, let’s pause and finish the rest at another time.

We have introduced two very important features in ES6, so now we can boldly say that ES6 will change our lives. These seemingly simple features are of great use.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template