DEV Community

Henry Williams
Henry Williams

Posted on

Using await/async in a Simple Script

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')
}
Enter fullscreen mode Exit fullscreen mode

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

Enter fullscreen mode Exit fullscreen mode

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')
    }
})()
Enter fullscreen mode Exit fullscreen mode

Top comments (2)

Collapse
 
misterhtmlcss profile image
Roger K.

Henry I like your idea here. What are your thoughts on where this could be a bad coding pattern and also where this would be a good pattern to use?

Collapse
 
henryjw profile image
Henry Williams

I generally don't like to use this pattern except for initializing something like a database connection or something of the sort at the end of the script.


module.exports.runQuery = async query => {
    ....
}

(async () => {
    await initializeDatabase()
})()
Enter fullscreen mode Exit fullscreen mode