Home >Web Front-end >JS Tutorial >How Do I Properly Execute Asynchronous Code at the Top Level in JavaScript?

How Do I Properly Execute Asynchronous Code at the Top Level in JavaScript?

DDD
DDDOriginal
2024-12-13 06:44:19221browse

How Do I Properly Execute Asynchronous Code at the Top Level in JavaScript?

Top-Level Execution of Asynchronous Code

In asynchronous programming, the async/await feature allows you to switch between synchronous and asynchronous tasks seamlessly. However, when executing asynchronous code at the top level, certain considerations must be made.

Explanation

When you define an async function, it returns a Promise. When you call this function at the top level, it immediately returns the Promise, not the resolved value. This is why your console outputs the Promise object before it executes the asynchronous task.

Solutions

To solve this, you have several options:

1. Top-level Await (ES2022 Proposal)

In modern environments, you can use top-level await in modules. This allows you to await a Promise directly in the module scope.

const text = await main();
console.log(text); // Logs the resolved value

2. Top-level Async Function with Unhandled Rejection

You can define a top-level async function that never rejects. This prevents unhandled rejection errors but doesn't handle errors explicitly.

(async () => {
  try {
    const text = await main();
    console.log(text); // Logs the resolved value
  } catch (e) {
    // Error handling (optional)
  }
})();

3. then() and catch()

If neither of the above options is suitable, you can use the Promise's then() and catch() methods to handle the result.

main()
  .then((text) => {
    console.log(text); // Logs the resolved value
  })
  .catch((err) => {
    // Error handling
  });

Note: In all cases, it's important to handle rejections properly to prevent unhandled rejection errors.

The above is the detailed content of How Do I Properly Execute Asynchronous Code at the Top Level in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:Roadmap for Next.jsNext article:Roadmap for Next.js