Javascript:承诺链与异步/等待? [英] Javascript : promise chain vs. async/await?

查看:56
本文介绍了Javascript:承诺链与异步/等待?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am learning about Javascript Promise and async/await. The sample code below asynchronously reads and parses a JSON file in node.js (my node.js version is v10.0.0).

在示例代码中,ChainReadJson函数和AwaitReadJson函数正在做相同的事情,读取并解析JSON文件.区别在于ChainReadJson函数使用一个Promise链,而AwaitReadJson函数使用async/await.

In the sample code, ChainReadJson function and AwaitReadJson function are doing the same thing, reading and parsing a JSON file. The difference is that ChainReadJson function uses a promise chain, while AwaitReadJson function uses 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函数的代码时,这些困难大多消失了.

When writing the code for ChainReadJson function using promise chain, I had difficulties controlling execution results and errors. However, when writing the code for AwaitReadJson function using async/await, those difficulties are mostly disappeared.

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

Do I correctly understand the benefits of async/await? What are the disadvantages of async/await compared to promise chain?

(示例代码是此答案中的代码的修改版本.原始代码仅使用promise链,并准确地知道错误在链中的何处发生了,什么是错误)

(The sample code is a modified version of the code in this answer. The original code uses promise chain only, and is written to know exactly where in the chain the error occurred and what is the error)

推荐答案

实际上,async/await设计,以减少样板,并使异步程序与回调,promise和生成器函数相比更容易编写.

Indeed, async/await were designed to reduce boilerplate and make asynchronous programs easier to write, compared to callbacks, promises, and generator functions.

  • 尽管promise的目标是相同的,但它们必须要在现有的JS引擎中工作,这还具有其他约束条件,因此其语法更加复杂. 使用异步/等待需要相对较新JS引擎.编写自己的node.js应用程序可能没关系,但是库可能需要与较旧的node.js版本兼容(而且我不确定如果您可以不使用生成器就可以将其转换以供较旧的浏览器使用).
  • 由于异步/等待是较新的,因此未优化.去年报告进行的比较Bluebird Promise(实现Promise简化版本的JS库)在一定的基准. (当然,当您的用例提出一些网络请求时,这可能并不重要.)
  • 您可能仍然需要保证并行执行多个异步操作(如果需要它们的结果)
  • While promises were created with the same goal, they had the additional constraint of having to work in the existing JS engines -- so their syntax is more complicated. Using async/await requires a relatively new JS engine. It might not matter if you're writing a node.js app of your own, but a library might need to be compatible with older node.js versions (and I'm not sure if you can transpile it for use in older browsers without generator support).
  • Since async/await is newer, it's not as optimized. A comparison made in the last year reports Bluebird promises (a JS library implementing simplified version of promises) outperforming async/await in a certain benchmark. (Of course this may not matter when your use-case is making a few network requests.)
  • You might still need promises to execute several asynchronous actions in parallel (edit: if you need their results)

这篇关于Javascript:承诺链与异步/等待?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆