Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 inLobby to conditionally run countPlayer, however I received a typeerror with no specific details.

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

like image 821
Sterling Archer Avatar asked Sep 24 '16 18:09

Sterling Archer


People also ask

Can you use await outside of an async function?

You can use the await keyword on its own (outside of an async function) within a JavaScript module.

Does await only works inside an async function?

As said, await only works inside async function. And await just waits for the promise to settle within the async function.

Does await require async?

Note: The await keyword is only valid inside async functions within regular JavaScript code. If you use it outside of an async function's body, you will get a SyntaxError . await can be used on its own with JavaScript modules.

Can you use await on a non promise?

This rule applies when the await operator is used on a non-Promise value. await operator pauses the execution of the current async function until the operand Promise is resolved.


1 Answers

There is always this of course:

(async () => {     await ...      // all of the script....   })(); // nothing else 

This makes a quick function with async where you can use await. It saves you the need to make an async function which is great! //credits Silve2611

like image 122
digerati-stratagies Avatar answered Oct 02 '22 13:10

digerati-stratagies