JS Coding Questions Logo
JS Coding Questions
#451💼 Interview💻 Code

How to use await outside of async function prior to ES2022?

Advertisement

728x90

Prior to ES2022, if you attempted to use an await outside of an async function resulted in a SyntaxError.

javascript
1await Promise.resolve(console.log("Hello await")); // SyntaxError: await is only valid in async function

But you can fix this issue with an alternative IIFE (Immediately Invoked Function Expression) to get access to the feature.

javascript
1(async function () {
2
3await Promise.resolve(console.log("Hello await")); // Hello await
4})();

In ES2022, you can write top-level await without writing any hacks.

javascript
1await Promise.resolve(console.log("Hello await")); //Hello await

Advertisement

Responsive Ad
🎯 Practice NowRelated Challenge

JavaScript Coding Exercise 22

Test your knowledge with this interactive coding challenge.

Start Coding

Advertisement

728x90
451of476
How to use await outside of async function prior to ES2022? | JSCodingQuestions.com