什么是ES6生成器,如何在node.js中使用它们? [英] What are ES6 generators and how can I use them in node.js?

查看:115
本文介绍了什么是ES6生成器,如何在node.js中使用它们?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我今天在一个node.js会议中,有人在那里遇到了node.js有es6生成器。他说这是一个比回调式编程更大的改进,并且会改变节点的景观。 Iirc,他说了一些关于调用堆栈和异常的事情。

I was at a node.js meetup today, and someone I met there said that node.js has es6 generators. He said that this is a huge improvement over callback style programming, and would change the node landscape. Iirc, he said something about call stack and exceptions.

我看了他们,但是并没有真正找到任何以初学者友好的方式解释他们的资源。什么是发电机的高级概述,以及不同于(或更好?)的回调?

I looked them up, but haven't really found any resource that explains them in a beginner-friendly way. What's a high-level overview of generators, and how are the different (or better?) than callbacks?

PS:如果你能给出一个代码片段,突出显示常见场景的差异(进行http请求或数据库调用)。

PS: It'd be really helpful if you could give a snippet of code to highlight the difference in common scenarios (making an http request or a db call).

推荐答案

发电机,光纤和协同程序



发电机是发电机)也是光纤或协程的基本建筑块。使用光纤,您可以暂停等待异步调用返回的功能,有效地避免在现场声明回调函数并创建闭包。回覆地狱说再见。

Generators, fibers and coroutines

"Generators" (besides being "generators") are also the basic buildings blocks of "fibers" or "coroutines". With fibers, you can "pause" a function waiting for an async call to return, effectively avoiding to declare a callback function "on the spot" and creating a "closure". Say goodbye to callback hell.


。关于调用堆栈和异常的一些事情

...he said something about call stack and exceptions

闭包的问题是即使他们神奇地保持回调的局部变量,闭包不能保持调用堆栈。

The problem with "closures" is that even if they "magically" keep the state of the local variables for the callback, a "closure" can not keep the call stack.

在回调的时候,通常,调用函数早已返回,所以调用函数上的任何catch块无法捕获异步函数本身或回调中的异常。这是一个大问题。因此,您不能将回调+闭包与异常捕获相结合。

At the moment of callback, normally, the calling function has returned a long time ago, so any "catch" block on the calling function cannot catch exceptions in the async function itself or the callback. This presents a big problem. Because of this, you can not combine callbacks+closures with exception catching.


...并将更改节点风格

...and would change the node landscape

如果使用生成器来构建一个帮助库,如 Wait.for-ES6 (我是作者),您可以完全避免回调和关闭,并且现在的catch块按预期工作,代码很简单。

If you use generators to build a helper lib like Wait.for-ES6 (I'm the author), you can completely avoid the callback and the closure, and now "catch blocks" work as expected, and the code is straightforward.


如果你能给出一个

It'd be really helpful if you could give a snippet of code to highlight the difference in common scenarios (making an http request or a db call).

检查 Wait.for-ES6 示例,查看与回调相同的代码和基于生成器的光纤。

Check Wait.for-ES6 examples, to see the same code with callbacks and with fibers based on generators.

这篇关于什么是ES6生成器,如何在node.js中使用它们?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆