How not to forget using await everywhere in Javascript?

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

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


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))

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(…) …
}());

Leave a Comment