Back
Close

JavaScript, async and await keywords

Magus
6,299 views
Previous: Error handling Next: Some tricks

await can only be used in an async function

You can't use await outside of an async function. The code will just crash if you try. When you are coding in a NodeJS environment, that means that you can't use await in the body directly. You have to use a function like this:

Use a main function
async function job() {
return 'test';
}
async function main() {
console.log(await job());
}
// Don't forget to call your main
main();
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Unhandled error

In NodeJS 8+, an unhandled error will trigger a warning. But the warning says that in later versions, it will be changed to a crash. You can see this warning with the following code:

Unhandled error
async function job() {
throw new Error('error');
}
job(); // The promise returned by the job function is in error but no one handle it
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
Create your playground on Tech.io
This playground was created on Tech.io, our hands-on, knowledge-sharing platform for developers.
Go to tech.io
codingame x discord
Join the CodinGame community on Discord to chat about puzzle contributions, challenges, streams, blog articles - all that good stuff!
JOIN US ON DISCORD
Online Participants