search
HomeWeb Front-endJS TutorialDetailed analysis of the Generator function in Es6

The Generator function is an asynchronous programming solution provided by ES6, and its syntactic behavior is completely different from traditional functions. This article introduces you to the relevant knowledge of the Es6 Generator function. Friends who are interested should take a look.

ECMAScript 6 (ES6 for short), as the next generation JavaScript language, brings JavaScript asynchronous programming into a new stage. .

The writing method of Generator function is very different from that of ordinary functions:

First, there is an asterisk between the function keyword and the function name;

Second, The yield statement is used inside the function body to define different internal states (yield means "output" in English).

This article focuses on introducing the Es6 Generator function to you. The specific content is as follows:

/*    一、generator函数的定义

    1.Generator 函数是 ES6 提供的一种异步编程解决方案,语法行为与传统函数完全不同
    2.形式上,Generator 函数是一个普通函数,但是有两个特征。一是,function关键字与函数名之间有一个星号;二是,函数体内部使用yield表达式,定义不同的内部状态
   */
  //定义一个generator函数 其内部有3种状态
  var helloGenerator = function *() {
    var next1 = yield 'hello';
    yield 'world' + next1;
    return 'ending';
  }
  //调用generator 函数和普通函数一样,直接加上双括号 () 但是跟普通函数的区别是generator不会立即执行, 返回的也不是函数的结果,而是内部的一个指针。
  var newGenerator = helloGenerator();
  //generator 函数是分段执行的 会从头部直到遇到下一个yield 表达式的时候停止下来。
  console.log(newGenerator.next('hahh')); //Object {value: "hello", done: false}
  console.log(newGenerator.next()); // {value: "worldhahh", done: false}
  console.log(newGenerator.next()); //{value: "ending", done: true}  done true| false true代表的意思内部yield 表达式已经执行完毕 false则相反
  console.log(newGenerator.next()); //{value: "undefined", done: true}
  /*
    总结一下,调用 Generator 函数,返回一个遍历器对象,代表 Generator 函数的内部指针。以后,每次调用遍历器对象的next方法,就会返回一个有着value和done两个属性的对象。value属性表示当前的内部状态的值,是yield表达式后面那个表达式的值;done属性是一个布尔值,表示是否遍历结束。
   */
  /*
    二、yield 表达式
    1.由于 Generator 函数返回的遍历器对象,只有调用next方法才会遍历下一个内部状态,所以其实提供了一种可以暂停执行的函数。yield表达式就是暂停标志。
    遍历器对象的next方法的运行逻辑如下。
    (1)遇到yield表达式,就暂停执行后面的操作,并将紧跟在yield后面的那个表达式的值,作为返回的对象的value属性值。
    (2)下一次调用next方法时,再继续往下执行,直到遇到下一个yield表达式。
    (3)如果没有再遇到新的yield表达式,就一直运行到函数结束,直到return语句为止,并将return语句后面的表达式的值,作为返回的对象的value属性值。
    (4)如果该函数没有return语句,则返回的对象的value属性值为undefined。
    2.yield 表达式和 return 语句的区别: return 不具有记忆功能, yield 具有记忆功能,下次调用next()方法的时候会接着往下执行。
    一个函数里面只能执行一个return 语句 可以执行多个yield 表达式。 yield 函数只能用在generator 函数里面不能用在其他函数里面,不然会报错。
   */
  /*
    三、与 Iterator 接口的关系
    任意一个对象的Symbol.iterator方法,等于该对象的遍历器生成函数,调用该函数会返回该对象的一个遍历器对象。由于 Generator 函数就是遍历器生成函数,因此可以把 Generator 赋值给对象的Symbol.iterator属性,从而使得该对象具有 Iterator 接口。
   */
  var myIterable = {};
  myIterable[Symbol.iterator] = function* () {
    yield 1;
    yield 2;
    yield 3;
  };
  console.log([...myIterable]) // [1, 2, 3]
  /*
    四、next 方法的参数
    yield表达式本身没有返回值,或者说总是返回undefined。next方法可以带一个参数,该参数就会被当作上一个yield表达式的返回值。
    意义:可以在 Generator 函数运行的不同阶段,从外部向内部注入不同的值,从而调整函数行为。
   */
  function* foo(x) {
    var y = 2 * (yield (x + 1));
    var z = yield (y / 3);
    return (x + y + z);
  }
  var a = foo(5);
  a.next() // Object{value:6, done:false}
  a.next() // Object{value:NaN, done:false}
  a.next() // Object{value:NaN, done:true}
  var b = foo(5);
  b.next() // { value:6, done:false }
  b.next(12) // { value:8, done:false }
  b.next(13) // { value:42, done:true }
  /*
    五、for...of 循环
    for...of循环可以自动遍历 Generator 函数时生成的Iterator对象,且此时不再需要调用next方法。(有点类似于 ... 对象的扩展运算符)
   */
  function* foo() {
    yield 1;
    yield 2;
    yield 3;
    yield 4;
    yield 5;
    return 6;
  }
  for (let v of foo()) {
    console.log(v);
  }
  // 1 2 3 4 5
  //上面代码使用for...of循环,依次显示 5 个yield表达式的值。这里需要注意,一旦next方法的返回对象的done属性为true,for...of循环就会中止,且不包含该返回对象,所以上面代码的return语句返回的6,不包括在for...of循环之中。
  //除了for...of循环以外,扩展运算符(...)、解构赋值和Array.from方法内部调用的,都是遍历器接口。这意味着,它们都可以将 Generator 函数返回的 Iterator 对象,作为参数。
  function* numbers () {
    yield 1
    yield 2
    return 3
    yield 4
  }
  // 扩展运算符
  [...numbers()] // [1, 2]
  // Array.from 方法
  Array.from(numbers()) // [1, 2]
  // 解构赋值
  let [x, y] = numbers();
  x // 1
  y // 2
  // for...of 循环
  for (let n of numbers()) {
    console.log(n)
  }
  // 1
  // 2
  /*
  六、Generator.prototype.throw()
   */
  function *testError(){
    try{
      yield ;
    }catch (e){
      console.log(e)
    }
  }
  var testE = testError();
  testE.throw(new Error('会出错吗?'));// 会出错吗? 这个错误是由generator 函数的内部捕获的。
  /*
    七、Generator.prototype.return()
    Generator 函数返回的遍历器对象,还有一个return方法,可以返回给定的值,并且终结遍历 Generator 函数。
   */
  function* gen() {
    yield 1;
    yield 2;
    yield 3;
  }
  var g = gen();
  g.next()    // { value: 1, done: false }
  g.return('foo') // { value: "foo", done: true }
  g.next()    // { value: undefined, done: true }

The above is what I compiled for you. I hope it will be helpful to you in the future.

Related articles:

Solve the problem of error when initializing vue2.0 dynamically bound image src attribute value

react to create- Create a project based on react-app

200 lines of code to implement blockchain Detailed explanation of blockchain examples

The above is the detailed content of Detailed analysis of the Generator function 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
Java vs JavaScript: A Detailed Comparison for DevelopersJava vs JavaScript: A Detailed Comparison for DevelopersMay 16, 2025 am 12:01 AM

JavaandJavaScriptaredistinctlanguages:Javaisusedforenterpriseandmobileapps,whileJavaScriptisforinteractivewebpages.1)Javaiscompiled,staticallytyped,andrunsonJVM.2)JavaScriptisinterpreted,dynamicallytyped,andrunsinbrowsersorNode.js.3)JavausesOOPwithcl

Javascript Data Types : Is there any difference between Browser and NodeJs?Javascript Data Types : Is there any difference between Browser and NodeJs?May 14, 2025 am 12:15 AM

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScript Comments: A Guide to Using // and /* */JavaScript Comments: A Guide to Using // and /* */May 13, 2025 pm 03:49 PM

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.