【问题标题】:Understanding Async Control Flow with Promises, Generators and Async/Await使用 Promises、Generators 和 Async/Await 了解异步控制流
【发布时间】:2019-01-08 15:14:56
【问题描述】:

为了更好地理解异步控制流,我阅读了几篇 stackoverflow 文章、博客文章和 Nodejs 设计模式书籍。现在,我可以轻松编写常规回调传递样式 (CPS) 代码。但是,我试图摆脱这种习惯并提高代码的可读性(或者,避免“回调地狱”)。我的问题是,我似乎将PromiseGeneratorAsync/Await 理解为单独的概念以及如何使用它们。但是,我不确定如何利用它们将 CPS 函数转换为没有嵌套。

为了帮助理解这个概念,我写了以下sn-p:

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}`);
})();

sn-p 运行,我得到了预期的结果。我的问题是:

  1. 这是“正确”的方法还是矫枉过正(promises + generators + async/await)?
  2. 这可以简单实现吗?

如果可能,我会很高兴有人指出一些以易于理解的方式解释场景和方法的资源。

【问题讨论】:

  • 我认为那里不需要发电机。为什么不只是await 每个Promise
  • @CertainPerformance 我想我明白你的意思。我删除了生成器,输出符合我的预期。

标签: javascript asynchronous promise async-await generator


【解决方案1】:
(async () => {

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

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

不需要生成器

生成器用于解释 async/await 的概念,因为它是两者的结合。 但是要使用 async/await 功能,您不再需要它们了

【讨论】:

  • let [fileContent, fileStat] = await Promise.all( readFile(fileLocation, 'utf8'), readStat(fileLocation) ); 如果您想同时启动两个异步操作,而不是在调用 readStat 之前等待 readFile 解决。
  • @Paulpro 只是想知道这不会导致竞争条件,因为两个函数都试图访问同一个文件?
  • @AbrarHossain 这是可能的。这取决于您是否需要 readStat 结果来反映最近的文件访问。如果您这样做,那么您确实需要先等待 readFile Promise 解决。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-25
  • 2013-04-11
  • 2019-01-17
  • 2019-07-03
  • 2019-12-21
  • 2019-03-06
相关资源
最近更新 更多