Using await/async in a Simple Script
Henry Williams
Posted on May 23, 2019
Problem:
You want to use await/async
at the top-level of your simple script like so:
async function asyncFunction() {
return new Promise(resolve => {
// simulate wait
setTimeout(resolve, 1000);
})
}
try {
// This won't work!
await asyncFunction()
} catch(err) {
console.error('Something bad')
}
Not so fast! await
can only be used within an async
function!
await asyncFunction()
^^^^^
SyntaxError: await is only valid in async function
at createScript (vm.js:80:10)
at Object.runInThisContext (vm.js:139:10)
at Module._compile (module.js:617:28)
at Object.Module._extensions..js (module.js:664:10)
at Module.load (module.js:566:32)
at tryModuleLoad (module.js:506:12)
at Function.Module._load (module.js:498:3)
at Function.Module.runMain (module.js:694:10)
at startup (bootstrap_node.js:204:16)
at bootstrap_node.js:625:3
Solution:
Enclose your code in an Immediately-Invoked Function Expression (IIFE).
async function asyncFunction() {
return new Promise(resolve => {
// Simulate wait
setTimeout(resolve, 1000);
})
}
// This works
(async () => {
try {
await asyncFunction()
} catch(err) {
console.error('Something bad')
}
})()
💖 💪 🙅 🚩
Henry Williams
Posted on May 23, 2019
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
javascript Mastering Advanced Error Handling in Express.js for Robust Node.js Applications
November 29, 2024