Home > Web Front-end > JS Tutorial > When Are Promise Constructor Callbacks Executed?

When Are Promise Constructor Callbacks Executed?

Susan Sarandon
Release: 2024-11-26 08:56:17
Original
903 people have browsed it

When Are Promise Constructor Callbacks Executed?

Understanding the Execution Timing of Promise Constructor Callback

When constructing a Promise object, the code provided within the callback function is not executed immediately but rather synchronously, as per the Promise specification. This means that the execution of the callback occurs as soon as the Promise is initialized.

Consider the following code snippet:

function doSomethingAsynchronous() {
  return new Promise((resolve) => {
    const result = doSomeWork();

    setTimeout(() => {
      resolve(result);
    }, 100);
  });
}
Copy after login

In this scenario, the function doSomeWork is invoked synchronously upon the construction of the Promise. The setTimeout function is used to delay the execution of the resolve function for demonstration purposes, but it does not affect the synchronous nature of the doSomeWork call.

The Promise specification mandates that the executor function (i.e., the callback provided to the constructor) is invoked immediately when the Promise is created. This ensures that the executor function's synchronous behavior is consistent, allowing for reliable handling of asynchronous processes and other tasks that may rely on its results.

The above is the detailed content of When Are Promise Constructor Callbacks Executed?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template