3

I have this code:

setTimeout(function timeout() { console.log('timeout'); }, 0); let p = new Promise(function(resolve, reject) { console.log('create promise'); resolve(); }); p.then(function(){ console.log('execute promise'); }); console.log('end');

I get this order when execute the code:

  • create promise
  • end
  • execute promise
  • timeout


Question: Why create promise is executed first? I expect to execute first end, because it is the only one synchrone code so it should be first executed.

3
  • 2
    the promise function is called immediately in most implementations. there's no need to defer its execution Commented Jan 29, 2022 at 15:19
  • @DanielA.White, then do i understand correct that all that is inside new Promise(...) is executed synchronously? Commented Jan 29, 2022 at 15:24
  • 2
    yes - the standard says so: tc39.es/ecma262/multipage/… Commented Jan 29, 2022 at 15:26

1 Answer 1

1

The callback passed to the Promise constructor is executed immediately and synchronously. But it is possible to start an asynchronous task in a Promise callback. Then the Promise resolves after the asynchronous task has completed. This is the primary use-case of Promises.

In your case there is no asynchronous task started, so all your cody is synchronous.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.