Last updated: Mar 4, 2024
Reading timeยท2 min
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('bobbyhadz.com'); (async () => { try { const value = await p; console.log(value); // ๐๏ธ "bobbyhadz.com" } 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 be 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.
I've also written a detailed guide on how to access the value of a promise.
We can 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('bobbyhadz.com'); try { const value = await p; console.log(value); // ๐๏ธ "bobbyhadz.com" } catch (err) { console.log(err); }
When using top-level await
, it is 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" }
If you use Node.js version 16.12.0
or more recent, you can use top-level
await
directly without changing anything.
If your Node.js version is 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 doesn't have a package.json
file, create one by issuing the
npm init -y
command.
npm init -y
Now you can use top-level await in your Node.js project.
const num = await Promise.resolve(42); console.log(num); // ๐๏ธ 42
However, as I previously mentioned, use a try/catch
block to make sure you
don't crash your application if a Promise is rejected or an error is raised.
const p = Promise.resolve(42); try { const num = await p; console.log(num); // ๐๏ธ 42 } catch (err) { console.log(err); }
You can learn more about the related topics by checking out the following tutorials: