几乎在任何地方都可以使用 async/await 吗? [英] Is it OK to use async/await almost everywhere?

查看:33
本文介绍了几乎在任何地方都可以使用 async/await 吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在编写小型 NodeJS CLI 工具供个人使用,我决定尝试使用 Babel 的 ES7 异步/等待功能.

I'm currently writing small NodeJS CLI tool for personal usage and I've decided to try ES7 async/await feature with Babel.

这是一个网络工具,所以我显然有异步网络请求.我为 request 包编写了一个简单的包装器:

It's a network tool so I obviously have asynchronous network requests. I wrote a simple wrapper for request package:

export default function(options) {
    return new Promise(function(resolve, reject) {
        request({...options,
            followAllRedirects: true,
            headers: {
                "user-agent": "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:47.0) Gecko/20100101 Firefox/47.0"
            }
        }, (error, response, body) => {
            if(error) {
                return reject(error);
            }
            resolve({response: response, body: body});
        });
    });
}

现在我可以做类似的事情

Now I can do something like

async function getGooglePage() {
    try {
        var r = await request({url: "http://google.com"});

        console.log(r.body);
        console.log("This will be printed in the end.")
    } catch(e) {
        console.log(e);
    }
}
getGooglePage();

现在我有一个问题:我在很多地方做请求,而且我必须将所有这些函数标记为 async,这是一个好的做法吗?我的意思是我的代码中几乎每个函数都应该是 async 因为我需要 await 其他 async 函数的结果.这就是为什么我认为我误解了 async/await 概念.

And now I have a question: I do requests in many places and I have to mark all these functions as async, is it a good practice? I mean that almost every function in my code should be async because I need to await a result from other async functions. That's why I think that I misunderstood async/await concept.

推荐答案

async/await 有时被称为传染性"或病毒性"(在 C# 世界中也是如此),因为为了使其有效,它需要在调用链的整个过程中得到支持.强制异步执行同步可能会导致意外结果,因此您应该将其从原始方法一直扩展到使用它的顶级使用者.换句话说,如果您创建或使用使用它的类型,该类型也应该实现它,依此类推.所以是的,您应该将 async 添加到本身依赖它的每个函数中.但是请注意,您不应将异步添加到实际上并未实现或不需要它的函数中.

async/await is sometimes called "contagious" or "viral" (or so it has in the C# world), because in order for it to be effective, it needs to be supported all the way down the call chain. Forcing something asynchronous to act synchronous can lead to unintended results, so you should extend it from the original method all the way down to the top level consumer using it. In other words, if you create or use a type that uses it, that type should also implement it, and so on all the way up the chain. So yes, it's expected that you add async to every function that itself relies on it. Just note, however, you should not add preemptively add async to functions that don't actually implement or need it.

想一想:如果你使用async(我的意思是通过awaiting),你就是async.避免将 async 调用压缩为同步调用.

Just think: If you use async (by awaiting something, I mean), you are async. Avoid squashing an async call into something synchronous.

这篇关于几乎在任何地方都可以使用 async/await 吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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