Reserving `await` within modules?

# Domenic Denicola (11 years ago)

I could swear someone brought this up before, but all I found was a thread about reserving await within arrow functions...

One of my great hopes for the ES7 await/async proposal would be that you could provide a top-level grammar wherein await was usable, without being inside of an async function. For example, this would allow Node.js scripts to be written without having to wrap in an IIAAFE:

const files = await Promise.all([fs.readFile("file.txt"), fs.readFile("file2.txt")];
console.log(files);

instead of

(async () => {
    const files = await Promise.all([fs.readFile("file.txt"), fs.readFile("file2.txt")];
    console.log(files);
}());

I would imagine future versions of Node (or an evolution of it) would readily embrace such a top-level grammar in favor of the current one.

Then I realized, we are already introducing a new top-level grammar in ES6, viz. module, which is clearly the path forward.

Could we reserve await inside the module grammar, so as to make it possible for future modules to await promises at top-level, without an IIAAFE? This would likely mean even web environments, with their very stringent backward-compatibility constraints, would be able to use this top-level await.

# Kevin Smith (11 years ago)

Could we reserve await inside the module grammar, so as to make it possible for future modules to await promises at top-level, without an IIAAFE? This would likely mean even web environments, with their very stringent backward-compatibility constraints, would be able to use this top-level await.

I don't think this will work given the staging that happens with module loading/linking/etc. But I have another option which I think will work just fine:

export async function main() {
  // your async code here
}

If you export a main function and run that from the command line (e.g. node my-module-with-main.js), the runtime executes the main module. This takes care of some other problems as well, like testing for whether or not the module is executed as a program versus a library.

Maybe?