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

When Are Promise Constructor Callbacks Executed?

Susan Sarandon
Susan SarandonOriginal
2024-11-26 08:56:17908browse

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);
  });
}

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!

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