如何不忘记在Javascript中使用等待? [英] How not to forget using await everywhere in Javascript?

查看:108
本文介绍了如何不忘记在Javascript中使用等待?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试编写一个小的chrome扩展,它依赖于 chrome。* 接口的回调密集查询功能,我很快就登陆了promises和async / await,因为我需要保证某些操作的顺序,同时试图避免回调地狱

Trying to write a little chrome extension, which relies on the callback-heavy query functions of the chrome.* interface, I quickly landed at promises and async/await, as I needed to guarantee the order of certain operations, while trying to avoid callback hell.

然而,一旦我将async / await引入某些函数,使用它们的每个函数也必须转换为异步函数为了能够等待返回值。最终甚至一些全局常数成为了承诺,例如

However, once I introduced async/await into some functions, every function that used them also had to be turned into an async function in order to be able to await the return value. Eventually even some global constants became promises, e.g.

const DEBUG = new Promise(function(resolve){
    chrome.management.getSelf(resolve);
}).then(function(self){
    return self.installType == 'development';
});

但是,现在我需要写 await 无处不在并引入奇怪的错误,如如果(DEBUG){...} 总是被执行变得太容易了。

However, now I need to write await everywhere and introducing weird bugs like if(DEBUG){...} always being executed becomes way too easy.

虽然似乎可能使用ESLINT 识别错误,写 await 到处都是不必要的麻烦,因此我想知道如果Javascript有一些我错过的更好的构造?

While it seems possible to identify the errors using ESLINT, writing await everywhere seems unnecessarily cumbersome and thus I was wondering if Javascript has some better construct that I am missing?

(主观上我目前对await / async的使用似乎是倒退;除非明确等待,否则Promise保持原样,但似乎我更愿意等待承诺默认情况下,在异步函数中,仅在明确请求时保留为裸承诺。)

(Subjectively my current use of await/async seems backwards; Promises are kept as-is unless explicitly awaited, but it seems more desirable to me to have promises awaited by default in async functions and kept as bare promises only when explicitly requested.)

推荐答案

缺少类型系统允许轻易捕捉到这样的错误(你认为T ypescript或Flow?),您可以使用匈牙利语系统表示法作为变量名称。选择后缀前缀,如 P 承诺 $ 并将其添加到所有promise变量中,类似于异步函数通常以 Async 后缀命名的方式。然后只做

For the lack of a type system that would allow to catch such mistakes easily (did you consider Typescript or Flow?), you can use Systems Hungarian Notation for your variable names. Choose a prefix of suffix like P, Promise or $ and add it to all your promise variables, similar to how asynchronous functions are often named with an Async suffix. Then only do things like

const debug = await debugPromise

你可以快速看到 if(debug)是好的但是 if(debugPromise)不是。

where you can quickly see that if (debug) is fine but if (debugPromise) is not.


一旦我将async / await引入某些函数,使用它们的每个函数也必须转换为异步函数,以便能够等待返回值。最终甚至一些全局常量变成了承诺

Once I introduced async/await into some functions, every function that used them also had to be turned into an async function in order to be able to await the return value. Eventually even some global constants became promises

我不会这样做。尽量使异步函数尽可能少。如果他们本身没有进行本质上异步的事情,而只依赖于某些承诺的结果,则将这些结果声明为函数的参数。一个简单的例子:

I would not do that. Try to make as few functions asynchronous as possible. If they are not doing intrinsically asynchronous things themselves but only rely on the results of some promises, declare those results as parameters of the function. A simple example:

// Bad
async function fetchAndParse(options) {
    const response = await fetch(options);
    // do something
    return result;
}
// usage:
await fetchAndParse(options)

// Good:
function parse(response) {
    // do something
    return result;
}
// usage:
await fetch(options).then(parse) // or
parse(await fetch(options))

同样的模式可以应用于全局变量 - 要么使它们成为每个函数的显式参数,要么使它们成为包含所有函数的模块函数的参数其他人作为封闭。然后 await 在声明或执行任何其他操作之前,只在模块中使用一次全局promise,并在之后使用普通结果值。

The same pattern can be applied for globals - either make them explicit parameters of every function, or make them parameters of a module function that contains all others as closures. Then await the global promises only once in the module, before declaring or executing anything else, and use the plain result value afterwards.

// Bad:
async function log(line) {
    if (await debugPromise)
        console.log(line);
}
async function parse(response) {
    await log("parsing")
    // do something
    return result;
}
… await parse(…) …

// Good:
(async function mymodule() {
    const debug = await debugPromise;
    function log(line) {
        if (debug)
            console.log(line);
    }
    function parse(response) {
        log("parsing")
        // do something
        return result;
    }
    … parse(…) …
}());

这篇关于如何不忘记在Javascript中使用等待?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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