Javascript : promise chain vs. 异步/等待?

标签 javascript node.js async-await es6-promise

我正在学习 Javascript Promiseasync/await。下面的示例代码异步读取并解析 node.js 中的 JSON 文件(我的 node.js 版本是 v10.0.0)。

在示例代码中,ChainReadJson 函数和 AwaitReadJson 函数做同样的事情,读取和解析 JSON 文件。区别在于ChainReadJson函数使用promise链,而AwaitReadJson函数使用async/await。

const FS = require("fs");

function ReadFile(fileName) {
    return new Promise((Resolve, Reject) => {
        FS.readFile(fileName, 'utf8', (error, result) => {
            if (error)
                Reject(error);
            else
                Resolve(result);
        });
    });
}

// function using promise chain

function ChainReadJson(fileName, CallBack) {
    ReadFile(fileName)
        .then(
            res => JSON.parse(res),
            err => {
                Message(-1, err.message);
            }
        )
        .then(
            res => {
                if (res !== undefined)
                    CallBack(fileName, res);
            },
            err => {
                Message(-2, err.message);
            }
        );
}

// function using async/await

async function AwaitReadJson(fileName, CallBack) {
    let res, json;

    try {
        res = await ReadFile(fileName);
    }
    catch (err) {
        Message(-1, err.message);
        return;
    }
    try {
        json = JSON.parse(res);
    }
    catch (err) {
        Message(-2, err.message);
        return;
    }
    CallBack(fileName, json);
}

ChainReadJson('test.json', PrintJSON);
AwaitReadJson('test.json', PrintJSON);

// common functions

function PrintJSON(fileName, json) {
    console.log(`JSON[${fileName}]:`, json);
}

function Message(n, str) {
    console.log(`[${n}]`, str);
}

在使用 Promise 链编写 ChainReadJson 函数的代码时,我很难控制执行结果和错误。但是,当使用 async/await 编写 AwaitReadJson 函数的代码时,这些困难大部分都消失了。

我是否正确理解异步/等待的好处?与 Promise 链相比,async/await 的缺点是什么?

(示例代码是the code in this answer的修改版本。原始代码仅使用promise链,并编写为确切知道错误发生在链中的哪个位置以及错误是什么)

最佳答案

确实,async/awaitdesigned与回调、promise 和生成器函数相比,减少样板文件并使异步程序更易于编写。

  • 虽然 Promise 的创建目标相同,但它们还有一个额外的限制,即必须在现有的 JS 引擎中工作——因此它们的语法更加复杂。 使用 async/await 需要 relatively new JS engine . 如果您正在编写自己的 node.js 应用程序可能无关紧要,但库可能需要与较旧的 node.js 版本兼容(我不确定您是否可以将其转换为在不支持生成器的旧浏览器中使用)。
  • 由于 async/await 较新,没有优化。去年的比较reports Bluebird Promise(一个实现简化版 Promise 的 JS 库)在某个基准测试中优于 async/await。 (当然,当您的用例发出一些网络请求时,这可能无关紧要。)
  • 您可能还会 need promises to execute several asynchronous actions in parallel (编辑:如果你需要他们的结果)

关于Javascript : promise chain vs. 异步/等待?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50223295/

相关文章:

c# - 使用 async/await 时处理节流/速率限制(429 错误)

node.js - Knex 记录插入乱序执行

javascript - CSS 以更好地显示图像预览

node.js - 与 Superagent 保持连接

node.js - 将 SSL (端口 443) 添加到 Nginx 反向代理服务器 (端口 80) - Nginx 配置文件

c# - 有时调用 CompleteAsync 方法时,Azure 设备客户端会抛出 DeviceMessageLockLostException

javascript - chrome 扩展中的弹出窗口?

javascript - 有没有办法使用 Jest toHaveBeenCalledWith 来检查参数数组长度?

javascript - 单击按钮时将表达式插入和删除到 div 中

javascript - 表单的 Web 自动化因设置输入值而失败