How to immediately run async functions without defining them as a new function

(Language: JavaScript)

This resource will help you immediately run async functions without defining them as a new function. This can be useful when you want to run multiple sections of async code without having to define each of them in functions.

This is known as Async IIFE (Immediately Invoked Function Expression).

Here’s how to do it:

(async () => {
  // run async code here

  // example usage:
  try {
    const response = await fetch('https://api.example.com/data');
    const data = await response.json();
    console.log(data.message);
  } catch (error) {
    console.error('An error occurred:', error);
  }
})();
1 Like

This doesn’t have to be async, you can use a normal function aswell. IIFEs are good for encapsulation (running small sections of code in a local scope), and organisation.

4 Likes