几乎到处都可以使用async / await吗? [英] Is it OK to use async/await almost everywhere?

查看:133
本文介绍了几乎到处都可以使用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.

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

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 因为我需要等待来自其他<$ c的结果$ c> 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/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 (通过 await 某事,我的意思是),你是 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天全站免登陆