简体   繁体   English

了解带有承诺,生成器和异步/等待的异步控制流

[英]Understanding Async Control Flow with Promises, Generators and Async/Await

I have read several stackoverflow posts, blog posts and Nodejs Design Patterns book in order to gain a better understanding of async control flow. 我已经阅读了几篇stackoverflow帖子,博客文章和Nodejs Design Patterns书籍,以更好地了解异步控制流。 Now, I am comfortable writing regular callback passing style (CPS) code. 现在,我很愿意编写常规的回调传递样式(CPS)代码。 However, I was trying to get out of the habit and improve readability of my code (or, avoid "callback hell"). 但是,我试图摆脱这种习惯并提高代码的可读性(或者避免使用“回调地狱”)。 My problem is, I seem to understand Promise , Generator and Async/Await as individual concepts and how to use them. 我的问题是,我似乎将PromiseGeneratorAsync/Await理解为单独的概念以及如何使用它们。 However, I am not sure how to take advantage of them to convert CPS functions to have no nesting. 但是,我不确定如何利用它们来转换CPS函数以使其没有嵌套。

To help understand the concept, I wrote the following snippet: 为了帮助理解这个概念,我编写了以下代码段:

const fs = require('fs');
const bluebird = require('bluebird');
const path = require('path');

// promisified fns
const readFile = bluebird.promisify(fs.readFile);
const readStat = bluebird.promisify(fs.stat);

function* tasks() {
    let fileLocation = path.resolve(__dirname, 'package.json');
    yield readFile(fileLocation, 'utf8');
    yield readStat(fileLocation);
}

(async () => {
    const taskRunner = tasks();
    let fileContent = await taskRunner.next().value;
    let fileStat = await taskRunner.next().value;

    console.log(`Content: ${fileContent}`);
    console.log(`Stats: ${fileStat}`);
})();

The snippet runs and I get the result I expected. 该代码段运行,我得到了预期的结果。 My questions are: 我的问题是:

  1. Is this the "right" approach or is this overkill (promises + generators + async/await)? 这是“正确”的方法,还是这种矫kill过正(承诺+生成器+异步/等待)?
  2. Can this be achieved simply? 可以简单地实现吗?

If possible, I would be glad if I'm pointed to some resources that explains the scenario and approaches in an easy to understand manner. 如果可能的话,如果我能以一些易于理解的方式指出一些解释场景和方法的资源,我将非常高兴。

(async () => {

    let fileContent = await readFile(fileLocation, 'utf8');
    let fileStat = await readStat(fileLocation);

    console.log(`Content: ${fileContent}`);
    console.log(`Stats: ${fileStat}`);
})();

No need for generator 无需发电机

Generators are used to explain the concept of async/await because it's a combination of the two. 生成器用于解释异步/等待的概念,因为它是两者的结合。 But to use async/await function you don't need them anymore 但是要使用异步/等待功能,您就不再需要它们了

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM