1

I had a look at the first example of JavaScript promise on the promise page on MDN. After I clicked 3 times fast on the Make a promise! button, I got the following result:

1) Started (Sync code started)
1) Promise started (Async code started)
1) Promise made (Sync code terminated)
2) Started (Sync code started)
2) Promise started (Async code started)
2) Promise made (Sync code terminated)
3) Started (Sync code started)
3) Promise started (Async code started)
3) Promise made (Sync code terminated)
2) Promise fulfilled (Async code terminated)
1) Promise fulfilled (Async code terminated)
3) Promise fulfilled (Async code terminated)

I totally understand that the lines Promise fulfilled can be inserted anywhere between the blocks of promise starting output (depending when the promise value actually becomes available), I don't understand why the Promise started lines are executed in sequence with Started and Promise made lines.

I would have expected an event to be place on the event queue, and the function passed to create a promise to be evaluated in its own context, after the Promise made instruction has completed.

It seems I missed something fundamental about promises, but I can't pinpoint what exactly.

Florent Georges
  • 2,190
  • 1
  • 15
  • 24
  • Can you describe what you expected in more detail? For example, how would you expect that output to look instead of what happened? – doldt Jul 18 '15 at 14:25
  • 2
    The "executor" function that you pass to `new Promise()` is called immediately. (That particular MDN page is absolutely terrible and doesn't explain that at all.) – Pointy Jul 18 '15 at 14:25
  • 1
    Everything inside a promise function is called synchronously unless/until it is either (1) waiting for the result of another promise or (2) waiting for a callback to be called. – Matt Browne Jul 18 '15 at 14:28
  • Thanks! So if I understand correctly, it is only when a function "tagged as asynchronous or blocking" (in this case `sleep`) that the promise function is deferred. But still, in case that example had not called `sleep`, the `then` function would execute asynchronously, right? – Florent Georges Jul 18 '15 at 14:43
  • 1
    @FlorentGeorges: `Promise` constructor callbacks ("resolver") are always called synchronously, `then` method callbacks ("onFulfilled") are always called asynchronously. – Bergi Jul 18 '15 at 15:00

0 Answers0