Home  >  Article  >  Web Front-end  >  What is the usage of generator in es6

What is the usage of generator in es6

WBOY
WBOYOriginal
2022-05-05 14:51:322117browse

In es6, generator is used to encapsulate asynchronous tasks. It is a container for asynchronous tasks, which allows the function to execute or pause according to the specified time; when defining the function, there is a between the function keyword and the function name. Asterisk (*), the syntax is "function *name(){..yield..}".

What is the usage of generator in es6

The operating environment of this tutorial: Windows 10 system, ECMAScript version 6.0, Dell G3 computer.

What is the usage of generator in es6

Generator is mainly asynchronous programming, used to encapsulate asynchronous tasks. It is a container for asynchronous tasks, allowing functions to be executed or paused at the time we specify.

The difference between defining a Generator function and defining an ordinary function is:

There is an * (asterisk) between the function keyword and the function name.

Yield is used inside the function to define the internal state of each function.

If there is a return statement inside the function, then it is the last state inside the function.

Use syntax:

function *name(){
...
yield; //需要暂停的时候加yield
...
yield;
...
}
const p = name();
p.next() //调用函数,执行到第一个yield处停止
p.next() //从上一个yeild开始执行,到下一个yield处为止

Let’s look at a simple example:

// 定义
function* sayHello() {
  yield 'hello';
  yield 'world';
  return 'ending';
}
// 调用
// 注意,hw获取到的值是一个遍历器对象
let g = sayHello();

The above example defines a Generator function named sayHello, which has two yields inside it expression and a return expression. Therefore, there are three states inside the function: hello, world and return statement (end execution). Finally, call this function to get a traverser object and assign it to the variable g.

The calling method of the Generator function is exactly the same as the ordinary function, function name (). The difference is:

  • After the function is called, the internal code (starting from the first line) will not be executed immediately.

  • There will be a return value after the function is called. This value is a pointer object pointing to the internal state. It is essentially a traverser object containing the internal state of the function.

[Related recommendations: javascript video tutorial, web front-end

The above is the detailed content of What is the usage of generator in es6. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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