当前位置: 首页 > 编程日记 > 正文

es6 generator_让我们探索一下ES6 Generators

es6 generator

by Tiago Lopes Ferreira

由Tiago Lopes Ferreira

让我们探索一下ES6 Generators (Let’s explore ES6 Generators)

Generators are an implementation of iterables.

生成器是可迭代对象的实现 。

The big deal about generators is that they are functions that can suspend its execution while maintaining the context.

生成器的重要之处在于它们是可以在保持上下文的同时暂停其执行的函数

This behaviour is crucial when dealing with executions that need to be paused, but its context maintained in order to recover it in the future.

在处理需要暂停的执行时,此行为至关重要,但是为了保持将来的恢复状态,必须保留其上下文。

Does async development sounds familiar here?

异步开发在这里听起来很熟悉吗?

句法 (Syntax)

The syntax for generators starts with it’s function* declaration (please note the asterisk) and the yield through which a generator can pause it’s execution.

生成器的语法从其function*声明(请注意星号 )和生成器可以暂停其执行的yield

Calling our generator function creates new generator that we can use to control the process through next function.

调用generator函数将创建新的生成器,我们可以使用它通过next函数来控制过程。

Running next will execute our generator’s code until an yield expression is reached.

next运行将执行generator的代码,直到达到yield表达式为止。

At this point the value on yield is emitted and the generator’s execution is suspended.

此时,将发出yield值,并暂停generator的执行。

(yield)

yield was born with generators and allow us to emit values. However, we can only do this while we are inside a generator.

yield是由发电机产生的,它使我们能够发出价值。 但是,只有在发电机内部时才能执行此操作。

If we try to yield a value on a callback, for instance, even if declared inside the generator, we will get an error.

例如,如果我们尝试在回调中yield一个值,即使在生成器中声明了该值,我们也会收到错误消息。

让* (yield*)

yield* was built to enable calling a generator within another generator.

yield*是为了能够在另一个生成器中调用生成器而构建的。

Our b iterator, produced by bar generator, does not work as expected when calling foo.

bar生成器生成的b迭代器在调用foo时无法按预期工作。

This is because, although the execution of foo produces an iterator, we do not iterate over it.

这是因为,尽管foo的执行会产生一个迭代器,但我们不会对其进行迭代。

That’s why ES6 brought the operator yield*.

这就是ES6带给运营商yield*

This works perfectly with data consumers.

这非常适合数据使用者。

Internally yield* goes over every element on the generator and yield it.

内部yield*遍历生成器上的每个元素并yield它。

生成器作为迭代器 (Generators as Iterators)

Generators are simple iterables, which means that they follow the iterable and iterator protocols:

生成器是简单的iterables ,这意味着它们遵循iterableiterator协议:

  • The iterable protocol says that an object should return a function iterator whose key is Symbol.iterator.

    iterable协议表示对象应返回其键为Symbol.iterator的函数迭代器。

  • The iterator protocol says that the iterator should be an object pointing to the next element of the iteration. This object should contain a function called next.

    iterator协议说迭代器应该是一个指向迭代的下一个元素的对象。 该对象应包含一个名为next的函数。

Because generators are iterables then we can use a data consumer, e.g. for-of, to iterate over generators’ values.

由于生成器是可迭代的,因此我们可以使用数据使用者(例如for-of )迭代生成器的值。

返回 (Return)

We can add a return statement to our generator, however return will behave differently according to the way generators’ data is iterated.

我们可以在生成器中添加return语句,但是return会根据生成器数据的迭代方式而有所不同。

When performing the iteration by hand, using next, we get our returned value (i.e. done) as the last value of our iterator object and our done flag as true.

手动执行迭代时,使用next ,我们获得返回值(即done )作为迭代器对象的最后一个value ,并且done标志为true。

On the side, when using a defined data consumer such as for-of or destructuring, the returned value is ignored.

在另一方面,当使用诸如for-ofdestructuring类的已定义数据使用者时,返回值将被忽略。

让* (yield*)

We saw that yield* allows us to call a generator inside a generator.

我们看到yield*允许我们在生成器内部调用生成器。

It also allow us to store the value returned by the executed generator.

它还允许我们存储执行的生成器返回的值。

(Throw)

We can throw inside a generator and next will propagate our exception.

我们可以throw放入生成器中,然后next将传播异常。

As soon as an exception is thrown the iterator flow breaks and it’s state is set to done: true indefinitely.

一旦引发异常,迭代器流程就会中断,并且其状态将设置为done: true无限期为done: true

生成者作为数据消费者 (Generators as Data Consumers)

Besides generators being data producers, through yield, they also have the ability to consume data using next.

除了生成器是数据生成器之外,它们还可以通过yield来使用next来使用数据。

There’s some interesting points to explore here.

这里有一些有趣的要点。

生成器创建(1) (Generator Creation (1))

At this stage we are creating our generator g.

在此阶段,我们正在创建生成器g

Our execution stops at point A.

我们的执行在A点停止。

第一下一个(2) (First next (2))

The first execution of next gets our generator to be executed until the first yield statement.

next的第一次执行使生成器一直执行到第一个yield语句。

On this first execution any value sent through next is ignored. This is because there’s no yield statement until the first yield statement ?

在第一次执行时,将忽略通过next发送的任何值。 这是因为没有yield的语句,直到第一个yield语句?

Our execution suspends at B waiting for a value to be filled to yield.

我们的执行在B暂停,等待填充一个值以yield

下一个下一个(3) (Next next (3))

On the next executions of next our generator will run the code until the next yield.

在next的next一次执行中,我们的生成器将运行代码,直到下一个yield为止。

In our case, it logs the value that is got through yield (i.e. Got: foo) and it gets suspended again on yield.

在我们的例子中,它记录通过yield获得的值(即Got: foo ),并再次在yield挂起。

用例 (Use Cases)

实施可迭代 (Implement Iterables)

Because generators are an iterable implementation, when created we get an iterable object, where each yield represents the value to emitted on each iteration. This description allow us to use generators to create iterables.

因为生成器是一个可迭代的实现 ,所以在创建时,我们得到一个可迭代的对象,其中每个yield表示每次迭代要发出的值。 此描述使我们可以使用生成器来创建可迭代对象。

The following example represents a generator as iterable that iterates over even numbers until max is reached. Because our generator returns an iterable we can use for-of to iterate over the values.

下面的示例将生成器表示为可迭代的生成器,该生成器将对偶数进行迭代直到达到max 。 因为我们的生成器返回一个可迭代的对象,所以我们可以使用for-of来迭代这些值。

It’s useful to remember that yield pauses the generator’s execution, and on each iteration the generator resumes from where it was paused.

记住, yield暂停生成器的执行,并且在每次迭代时,生成器都会从暂停的位置恢复,这很有用。

异步代码 (Asynchronous Code)

We can use generators to better work with async code, such as promises.

我们可以使用生成器更好地处理异步代码,例如promises

This use case it a good introduction to the new async/await on ES8.

这个用例很好地介绍了ES8上的新async/await

Next is an example of fetching a JSON file with promises as we know it. We will use Jake Archibald example on developers.google.com.

接下来是一个示例,该示例使用我们知道的带有promises的JSON文件。 我们将在developers.google.com上使用Jake Archibald示例。

Using co library and a generator our code will look more like synchronous code.

使用co库和生成器,我们的代码将看起来更像同步代码。

As for the new async/await our code will look a lot like our previous version.

至于新的async/await我们的代码看起来很像我们以前的版本。

结论 (Conclusion)

This is schema, made by Axel Rauschmayer on Exploring ES6 show us how generators relate with iterators.

这是由Axel Rauschmayer在“ 探索ES6”中制作的模式,向我们展示了生成器与迭代器之间的关系。

Generators are an implementation of iterables and follow the iterable and iterator protocol. Therefore they can be used to build iterables.

生成器是可迭代的实现,并遵循iterableiterator协议。 因此,它们可用于构建可迭代对象。

The most amazing thing about generators is their ability to suspend their execution. For this ES6 brings a new statement called yield.

生成器最令人惊讶的是它们具有暂停执行的能力。 为此,ES6带来了一个称为yield的新声明。

However, calling a generator inside a generator is not as easy as executing the generator function. For that, ES6 has yield*.

但是,在生成器内部调用生成器并不像执行生成器功能那样容易。 为此,ES6具有yield*

Generators are the next step to bring asynchronous development close to synchronous.

生成器是使异步开发接近于同步的下一步。

谢谢 ? (Thanks to ?)

  • Axel Rauschmayer for his Exploring ES6 — Generators

    Axel Rauschmayer的探索性ES6 —发电机

  • Nicolás Bevacqua for his PonyFoo — ES6 Generators in Depth

    尼古拉斯·贝瓦夸 ( NicolásBevacqua)的PonyFoo-深入研究ES6生成器

  • Jake Archibald for his promises example on developers.google.com

    杰克·阿奇博尔德 ( Jake Archibald)在developers.google.com上的承诺示例

  • To all Regular Show fans

    致所有常规节目迷

Be sure to check out my other articles on ES6

请务必查看我有关ES6的其他文章

Demystifying ES6 Iterables & IteratorsLet’s demystify JavaScript new way to interact with data structures.medium.freecodecamp.com

揭开ES6迭代器和迭代器 的神秘 面纱 让我们揭开JavaScript与数据结构交互的新方式的神秘 面纱 medium.freecodecamp.com

翻译自: https://www.freecodecamp.org/news/lets-explore-es6-generators-5e58ed23b0f1/

es6 generator

相关文章:

没听说过这些,就不要说你懂并发了,three。

引言 很久没有跟大家再聊聊并发了,今天LZ闲来无事,跟大家再聊聊并发。由于时间过去的有点久,因此LZ就不按照常理出牌了,只是把自己的理解记录在此,如果各位猿友觉得有所收获,就点个推荐或者留言激励下LZ&am…

设计模式之代理模式(Proxy Pattern)

定义:为其他对象提供一种代理以控制这个对象的访问,也叫做委托模式。 咱们比作游戏,通俗讲代理模式就是,一个主题虚基类派生出两个子类,一个玩家类,实现相关操作,一个是代练类,代替执…

[微信小程序]给data的对象的属性赋值

有问题可以扫码加我微信&#xff0c;有偿解决问题。承接小程序开发。 微信小程序开发交流qq群 173683895 、 526474645 &#xff1b; 正文&#xff1a; <view wx:for"{{leixing}}"><button class"leixing_btn {{user_infor.lx_btnitem.divingtype…

无家可归的iPhone

by Fabrice Dubois通过Fabrice Dubois 无家可归的iPhone (Homeless iPhone) So, apparently the next iPhone won’t have a physical Home button. There’s been much speculation already about what that means for the user. The bottom area of the device, for some, w…

Spring 自动化装配Bean

声明一张cd的接口&#xff1a; public interface CompactDisc {public abstract void play(); } 实现cd接口&#xff1a; Component("SgtPeppers") public class SgtPeppers implements CompactDisc {private String title "Sgt.Peppers Lonely Hearts Club Ba…

js中函数,方法,事件对比区分,什么是方法,什么是函数

微信小程序开发交流qq群 581478349 承接微信小程序开发。扫码加微信。 正文&#xff1a; 简单的理解&#xff1a;函数是运行在本地的&#xff0c;方法是公用的。 事件是开关&#xff0c;通过某某事件触发某个函数 通常命名规范 函数的命名使用小写字母和下划线&#xff…

笔记 JVM调优流程

待续 转载于:https://www.cnblogs.com/leeeee/p/7276287.html

创建新的apple id_Google是新的Apple吗?

创建新的apple idby Sumit Gupta由Sumit Gupta Google是新的Apple吗&#xff1f; (Is Google the new Apple?) 随着众多设备的推出&#xff0c;谷歌试图击败苹果。 “由Google制造”会使Google更像Apple吗&#xff1f; (With the launch of numerous devices, Google is tryi…

yeomen/bower/grunt

yeomen: npm install yo angular-in-action project npm install -g generator-angular npm install -g genrator-webapp yo angular learnangular new angular project yo webapp grunt-by-yeomen package.json npm install (执行package.json所指定的依赖包) bower: npm ins…

Window Server 2008 R2 安装 Share Point 2013

原文地址&#xff1a;http://www.cnblogs.com/jianyus/p/3631905.html转载于:https://www.cnblogs.com/gaobing/p/4191060.html

esp freertos_如何开始使用FreeRTOS和ESP8266

esp freertosby Denis Nuțiu丹尼斯努尤(Denis Nuțiu) 如何开始使用FreeRTOS和ESP8266 (How to get started with FreeRTOS and ESP8266) Recently, I purchased a NodeMCU from AliExpress for about $4. The reason I did this was to find out what all the fuss is about…

[SCOI2007]修车

题目描述 同一时刻有N位车主带着他们的爱车来到了汽车维修中心。维修中心共有M位技术人员&#xff0c;不同的技术人员对不同的车进行维修所用的时间是不同的。现在需要安排这M位技术人员所维修的车及顺序&#xff0c;使得顾客平均等待的时间最小。 说明&#xff1a;顾客的等待时…

[微信小程序]时间戳转日期

有问题可以扫码加我微信&#xff0c;有偿解决问题。承接小程序开发。 微信小程序开发交流qq群 173683895 、 526474645 &#xff1b; 正文&#xff1a; // util.js //时间戳转换成日期时间 function js_date_time(unixtime) {var dateTime new Date(parseInt(unixtime) …

React模式:集中式PropTypes

通过集中化PropType避免重复自己 (Avoid repeating yourself by centralizing PropTypes) There are three popular ways to handle types in React: PropTypes, TypeScript and Flow. This post is about PropTypes, which are currently the most popular.在React中有三种流行…

Java Class SecurityManager

# 前言 简单了解 SecurityManager。具体查阅 API。 # What 它是 Java 沙盒模型控制安全的重要一个环节。它是 Java 的一个类。下面一段话源于SecurityManager API&#xff1a; The security manager is a class that allows applications to implement a security policy. It a…

微信小程序,对象转换成数组

有问题可以扫码加我微信&#xff0c;有偿解决问题。承接小程序开发。 微信小程序开发交流qq群 173683895 、 526474645 &#xff1b; 正文&#xff1a; 对象转数组: var jiu res.data.k4.f3var nArr [];for (var i in jiu){nArr.push(jiu[i]);}console.log(jiu);consol…

sql 事务使用

BEGIN TRAN Tran_Money --开始事务DECLARE tran_error int; SET tran_error 0;BEGIN TRY UPDATE tb_Money SET MyMoney MyMoney - 30 WHERE Name 刘备;SET tran_error tran_error ERROR;--测试出错代码&#xff0c;看看刘备的钱减少&#xff0c;关羽的钱是否会增加--SE…

一群算法_树遍历解释:他们就像一群懒惰的学生,试图欺骗他们的考试

一群算法by Sachin Malhotra由Sachin Malhotra 树遍历解释&#xff1a;他们就像一群懒惰的学生&#xff0c;试图欺骗他们的考试 (Tree Traversals explained: They’re like a class of lazy students trying to cheat on their exam) Imagine that you are enrolled in a mat…

微信小程序转发 分享 打电话功能,完整代码附效果图

微信小程序开发交流qq群 581478349 承接微信小程序开发。扫码加微信。 正文&#xff1a; 按钮绑定在页面内发起转发事件onShareApp:(注意这里是button 并且给他设置了open-type"share" 属性) <button classbottom_1 bottom_1_zf open-type"share" bi…

《DSP using MATLAB》示例 Example 6.25

代码&#xff1a; % x [-0.9, 0.81]; [y, L, B] QCoeff(x, 3) % Unquantized parameters r 0.9; theta pi/3; a1 -2*r*cos(theta); a2 r*r; p1 r*exp(j*theta); p2 p1;% Quantized parameters: N 3; [ahat, L, B] QCoeff([a1, a2], 3); rhat sqrt(ahat(2)); thetah…

sqlserver查询自定义的函数

1)sp_helptext同样适应用自定义函数 2)sys.sql_modules表也可以查 查看函数的源代码: exec sp_helptext 函数名转载于:https://www.cnblogs.com/toSeeMyDream/p/4195030.html

辍学的名人_我辍学去追求成为网络开发人员和设计师的梦想

辍学的名人by Carlos Sz由Carlos Sz 我辍学去追求成为网络开发人员和设计师的梦想 (I dropped out of college to pursue my dreams of being a web developer and designer) When I was 14, I discovered HTML. Thanks to my computer science teacher at school. And from t…

Java中的static关键字的用法

1.静态方法 static&#xff1a;通常在一个类中定义一个方法为static&#xff0c;那就是说&#xff0c;无需本类的对象即可调用此方法 声明为static的方法有以下几条限制&#xff1a; &#xff08;1&#xff09;它们仅能调用其他的static方法。 &#xff08;2&#xff09;它们只…

[微信小程序]上传单张和多张图片

微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 上传单张图片并展示, <button bindtap"upimg" classjia_img >上传</button> <image src"{{tempFilePaths[0]}}"></image> data{ tempFilePaths:[]; },u…

“猪”飞起来了吗

&#xff08;让我们用代码改变世界&#xff0c;也让代码改变自己的生活&#xff09; 台风来了&#xff0c;猪都能飞起来。 这是投资者对A股近期走势最生动的形容。当成交量不断的刷新纪录&#xff0c;直冲1.2万亿天量成交时&#xff0c;股指的高度也在不断的被刷新&#xff0c;…

微信公众号开发本地环境开发_如何在5分钟内使HTTPS在本地开发环境上工作

微信公众号开发本地环境开发Almost any website you visit today is protected by HTTPS. If yours isn’t yet, it should be. Securing your server with HTTPS also means that you can’t send requests to this server from one that isn’t protected by HTTPS. This pos…

pcntl_fork 导致 MySQL server has gone away 解决方案

pcntl_fork 前连数据库&#xff0c;就会报 MySQL server has gone away 错误。原因是子进程会继承主进程的数据库连接&#xff0c;当mysql返回数据时&#xff0c;这些子进程都可以通过这个连接读到数据&#xff0c;造成数据错乱。 该操作数据库的地方还是要操作数据库&#xff…

[微信小程序]滚动选择器

微信小程序开发交流qq群 581478349 承接微信小程序开发。扫码加微信。 正文&#xff1a; <view class"section"><view class"section__title">普通选择器</view><picker bindchange"bindPickerChange" value"{{ind…

北航MOOC客户端

我们的团队作业终于完成了&#xff0c;欢迎下载使用我们的北航MOOC手机客户端软件&#xff08;Android端&#xff09;——北航学堂&#xff0c;学习北航的公开课程。 安装包下载地址&#xff1a; http://pan.baidu.com/s/1jGvH7fS 团队发布博客 http://www.cnblogs.com/sevens/…

大学毕业没有实习经历_我是如何在大学毕业后没有实习的情况下获得第一份开发人员工作的...

大学毕业没有实习经历by Tim Park蒂姆帕克(Tim Park) 我是如何在大学毕业后没有实习的情况下获得第一份开发人员工作的 (How I got my first developer job with no internships straight out of college) 5个关键要素&#xff0c;将在求职中发挥重要作用 (5 key elements tha…