Please consider this code:
function testPromise() {
resolver = function(resolve, reject) {
resolve('foo');
console.log('@resolver');
}
setTimeout(() => console.log('Timeout'), 0);
console.log('Before');
const p = new Promise(resolver);
console.log(p);
p.then((value) => console.log('@then1:', value));
p.then((value) => console.log('@then2:', value));
console.log('After');
}
Running this function gives the following output in Firefox console:
Before
@resolver
Promise { <state>: "fulfilled", <value>: "foo" }
After
@then1: foo
@then2: foo
Timeout
Although the promise executor doesn't do anything asynchronous and calls the resolve
callback parameter right away, and the console output confirms that the promise state is fulfilled
, nevertheless the callback function that is passed to promise's then()
method is called later, after execution of the currently running code is finished. I could get the same results if the resolve()
call would be put in setTimeout
: setTimeout(() => resolve('foo'), 0);
I'd like to understand more about this behavior: when exactly this then
callback is called? Immediately after the currently executed code exits? Or there could be some other queued-up code that gets executed before? From the test code above, it can be observed that the zero-time timeout callback is executed later.