how can i use top level `await` in nodejs

2024-06-25by@tim&@ChatGPT.Model: GPT-4o
tim

how can i use top level await in nodejs

Avatar
Avatar

Using top-level await in Node.js allows you to use the await keyword outside of an async function. This feature is available in Node.js starting from version 14.8.0, but it's officially stable and more widely used in version 16 and later. Here’s how you can use top-level await in Node.js:

  1. Ensure you're using a supported version of Node.js: Make sure your Node.js version is 14.8.0 or higher. You can check your Node.js version by running:

    node -v
    
  2. Use an ES module: Top-level await is supported in ES modules. You can specify an ES module by either naming your file with a .mjs extension or by adding "type": "module" in your package.json file.

    • Using a .mjs file:

      Create a file named example.mjs:

      // example.mjs
      const fetchData = async () => {
          // Simulating an async operation like fetching data
          return new Promise((resolve) => setTimeout(() => resolve("Data fetched"), 1000));
      };
      
      const data = await fetchData();
      console.log(data);  // Output: Data fetched
      

      Run the file using Node.js:

      node example.mjs
      
    • Using package.json with "type": "module":

      Update your package.json:

      {
          "type": "module"
      }
      

      Create a file named example.js:

      // example.js
      const fetchData = async () => {
          // Simulating an async operation like fetching data
          return new Promise((resolve) => setTimeout(() => resolve("Data fetched"), 1000));
      };
      
      const data = await fetchData();
      console.log(data);  // Output: Data fetched
      

      Run the file using Node.js:

      node example.js
      
  3. Dealing with CommonJS (optional): If you need to use top-level await in a CommonJS module (files with .cjs extension or default in Node.js when package.json does not specify "type": "module"), you can use an immediately-invoked async function expression (IIAFE) as a workaround:

    // example.cjs
    (async () => {
        const fetchData = async () => {
            // Simulating an async operation like fetching data
            return new Promise((resolve) => setTimeout(() => resolve("Data fetched"), 1000));
        };
    
        const data = await fetchData();
        console.log(data);  // Output: Data fetched
    })();
    

    Run the file using Node.js:

    node example.cjs
    

By following these steps, you can effectively use top-level await in your Node.js applications.