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
?
You can use the await keyword on its own (outside of an async function) within a JavaScript module.
As said, await only works inside async function. And await just waits for the promise to settle within the async function.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With