Sterling Archer Sterling Archer - 10 months ago 48
Javascript Question

Using await outside of an async function

I was attempting to chain two async functions together, because the first had a conditional return parameter that caused the second to either run, or exit the module. However, I've found odd behavior I can't find in the specs.

async function isInLobby() {
//promise.all([chained methods here])
let exit = false;
if (someCondition) exit = true;

This is a bastardized snippet of my code (you can see the full scope here), that simply checks if a player if already in a lobby, but that's irrelevant.

Next we have this async function.

async function countPlayer() {
const keyLength = await scardAsync(game);
return keyLength;

This function doesn't need to run if
exit === true

I tried to do

const inLobby = await isInLobby();

This I hoped would await to results, so I can use
to conditionally run
, however I received a typeerror with no specific details.

Why can't you
function outside of the scope of the function? I know it's a sugar promise, so it must be chained to
but why is it that in
I can await another promise, but outside, I can't

Answer Source

Top level await is not supported. There are a few discussions by the standards committee on why this is, such as this Github issue.

There's also a thinkpiece on Github about why top level await is a bad idea. Specifically he suggests that if you have code like this:

// data.js
const data = await fetch( '/data.json' );
export default data;

Now any file that imports data.js won't execute until the fetch completes, so all of your module loading is now blocked. This makes it very difficult to reason about app module order, since we're used to top level Javascript executing synchronously and predictably. If this were allowed, knowing when a function gets defined becomes tricky.