Borislav Hadzhiev
Last updated: Dec 23, 2021
Check out my new book
There are multiple ways to use the await
operator outside of an async
function:
16.12.0
or set type
to module
in your
package.json
file if using Node version 14.8.0 - 16.11.0
.type
to module
in the script
tag.Here is the most widely supported approach - using an immediately invoked function expression.
// 👇️ Example promise const p = Promise.resolve('Hello world'); (async () => { try { const value = await p; console.log(value); // 👉️ "Hello world" } catch (err) { console.log(err); } })();
Technically, we are defining an async
function here, however we call the
function immediately and get access to the resolved value.
If the promise is rejected, the reason for its rejection will get passed to the
catch
block.
If you're working on the client side, you can check the browser support for the
top level await feature in
this caniuse
table.
At the time of writing, we are able to use the top level await
feature by
setting the type
attribute to module
when loading the JS file.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <!-- ✅ type is set to module ✅ --> <script type="module" src="index.js"></script> </body> </html>
This enables us to use top level await directly.
const p = Promise.resolve('Hello world'); try { const value = await p; console.log(value); // 👉️ "Hello world" } catch (err) { console.log(err); }
await
, it's very important to use a try/catch
block because an uncaught exception caused by a rejected promise might stop your application from running.// 👇️ Example rejected promise const p = Promise.reject('Something went wrong'); try { const value = await p; console.log(value); } catch (err) { // 👇️ catch the error here console.log(err); // 👉️ "Something went wrong" }
16.12.0
, you can directly use top level await
without changing anything.If your Node.js version in in the range 14.8.0 - 16.11.0
, you need to set the
type
property to module
in your package.json
file.
{ "type": "module", // ...rest }
If your project does not have a package.json
file, you can create one by
issuing the npm init -y
command.