-3

In the following code how does JavaScript determine that the state of myPromise has become "fulfilled"? I.e., how is the determination made that it's time to put the .then() handler into the microqueue for subsequent execution?

const myPromise = new Promise(function(resolve, reject) {
    setTimeout(function() {
        resolve('Resolved  promise: ');
    }, 2000);
});

myPromise.then((resolvedValue) => {
    console.log(resolvedValue + 'The .then() handler is now running');
});

// Output (after ~2 seconds): "Resolved promise: The .then() handler is now running"

Andy
  • 7
  • 3
  • 1
    You should refer to the [Promise Documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) – Jaxon Crosmas Aug 06 '22 at 01:59
  • 1
    Not sure exactly what you're confused about. If you're looking for the precise spec details of how a `.then`'s callback runs, see here: https://tc39.es/ecma262/#sec-promise.prototype.then – CertainPerformance Aug 06 '22 at 01:59
  • Maybe [How is a promise/defer library implemented?](https://stackoverflow.com/questions/17718673/how-is-a-promise-defer-library-implemented) – ggorlen Aug 06 '22 at 02:26
  • Jake Archibald has done a great [presentation about the event loop](https://youtu.be/cCOL7MC4Pl0). Perhaps this will answer your question? – Oskar Grosser Aug 06 '22 at 02:33

1 Answers1

0

Answer

You calling the function resolve changes the state of the promise, thus JS can know that the promise's state has changed by you calling resolve.

The callback attached to that promise with .then() will then be known to be scheduled (as a microtask).

Explaining your code

You instantiate a new Promise and provide a callback that is run immediately. The callback schedules a task to run after 2000ms. That task will resolve the promise upon execution.

After having constructed the promise, you then attach a callback via .then() to the returned promise. This will only execute once the promise has fulfilled.

Now your synchronous code has run to completion, so the event loop has time to execute another task. The next task may be the one after 2000ms, which resolves the promise (and therefore sets its state to "fulfilled").

Once the task to resolve the promise has finished executing, a microtask will be scheduled to run immediately after: That microtask will run the .then() callback. This will finally log your string.

Oskar Grosser
  • 2,804
  • 1
  • 7
  • 18