异步生成区块_使用生成器异步控制流

异步生成区块

When we want to execute a set of independent tasks one after another, we do not care about the result returned from each task but all we care about is executing them one after another. In this article, I will walk you through the primary use-case for generators: Asynchronous control flow.

当我们要一个接一个地执行一组独立的任务时,我们不在乎每个任务返回的结果,但我们关心的只是一个接一个地执行它们。 在本文中,我将带您了解生成器的主要用例:异步控制流。

什么是发电机,它们如何工作? (What are generators and how do they work ?)

If you're already familiar with how generators work, you can skip this section.

Generators are special functions that can be run, paused and resumed at different stages of their execution, thanks to the special keyword yield.

由于特殊关键字yield ,生成器是可以在执行的不同阶段运行,暂停和恢复的特殊功能。

here is a simple example of an ES6 generator

这是一个ES6生成器的简单示例

function* myGenerator() {
yield ‘first’;
let input = yield ‘second’;
yield input;
}// Getting the generator object
let gen = myGenerator();// Launching the generator
console.log(gen.next()): // { value: ‘first’, done: false }// First resume (no passed value)
console.log(gen.next()); // { value: ‘second’, done: false }// First resume (pass a value)
console.log(gen.next(‘third’)); // { value: ‘third’, done: false }// Last (no more yield)
console.log(gen.next()); // { value: undefined, done: true }

So, what just happened here ?

那么,这里发生了什么?

  • We declared a generator function using the special syntax function* myfunction() {}

    我们使用特殊语法函数* myfunction(){}声明了生成器函数

  • Calling this function at first returns a generator object. This object has a method next to resume the generator function at its current state.

    首先调用此函数将返回一个生成器对象 。 该对象接下来有一个方法可以在其当前状态恢复生成器功能。

  • The generator function does not start its execution until the first gen.next is triggered.

    在触发第一个gen.next之前,生成器函数不会开始执行。

  • Each time gen.next is called, the generator function is resumed and run until the next yield. the gen.next call returns an object containing the yielded value and a flag telling if the generator function has ended or not.

    每次调用gen.next时 ,将恢复并运行generator函数,直到下一个yield为止。 gen.next调用返回一个对象,该对象包含产生的值和一个标志,该标志指示生成器函数是否已结束。

  • You may also have noticed that we can pass data to the generator function.

    您可能还注意到,我们可以将数据传递给generator函数。

异步控制流程 (Asynchronous control flow)

Let’s say that we want to generate a pdf file on the backend and then use the generated file to send an email. Our code using promises might look like this.

假设我们要在后端生成pdf文件,然后使用生成的文件发送电子邮件。 我们使用promise的代码可能如下所示。

function generatePdf(pdfId) {
return fetch(`/generate/${pdfId}/pdf`, {
method: ‘get’
}).then(response => response.json());
}function sendEmail(urlPdf, email) {
return fetch(‘/email’, {
method: ‘post’,
body: JSON.stringify({
pdf: urlPdf
email: email
})
}).then(response => response.json());
}generatePdf(pdfId)
.then(result => sendEmail(result.urlPdf, result.email))
.then(responseMessage => {
console.log(responseMessage);
})
.catch(err => {
console.log(err);
});

We can do better and make this looks more synchronous using generators. Here is what we get:

我们可以做得更好,并使用生成器使其看起来更加同步。 这是我们得到的:

import { takeLatest } from "redux-saga";function* watchEvents() {
yield takeLatest('LOAD', load);
}function* load() {
try {
const result = yield generatePdf(pdfId);
yield sendEmail(result.urlPdf, result.email);
} catch (error) {
console.log(error);
}

In the above example I used the Redux-Saga, is a an alternative side effect model for Redux applications. It handles all the asynchronous control flow of Redux applications in a central place using … guess what, 😄 generators.

在上面的示例中,我使用了Redux-Saga,它是Redux应用程序的替代副作用模型。 它使用…猜生成器来在中心位置处理Redux应用程序的所有异步控制流。

These small utilities work by yielding to a function which returns a promise. When that promise resolves, it calls the generator’s next() function, resuming execution.

这些小型实用程序通过产生返回承诺的函数来工作。 当该承诺解决时,它将调用生成器的next()函数,以恢复执行。

In hand you are now empowered to write cleaner, simpler, more maintainable asynchronous javascript!

现在,您已经可以编写更简洁,更简单,更可维护的异步javascript!

翻译自: https://medium.com/@rafael.mosias2/use-generators-to-asynchronous-control-flow-f11dad4e5e89

异步生成区块

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值