简体   繁体   中英

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. Now, I am comfortable writing regular callback passing style (CPS) code. 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. However, I am not sure how to take advantage of them to convert CPS functions to have no nesting.

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)?
  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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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