I have this peace of code:
const mql = window.matchMedia('(min-width: 400px)');
mql.addListener(e => {
if (e.matches)
console.log('Match!');
});
Promise.resolve('Resolved').then(console.log);
When I execute it on Chrome, the output is 'Resolved' and after 'Match'. However on Firefox, it is the opposite.
I do not understand why it is different? Is it possible to force the execution order?
According to the event loop specs, microtasks are executed before any rendering callbacks. Unfortunately, none of the browsers stick to the specs. Chrome is far to be the closest and that's why the Promise being a microtask is executed first. Firefox is out of the specs.
You can look at this link for more information and discrepancies about the Event Loop https://github.com/atotic/event-loop
As a rule of thumb, never depend on the execution order except if you have callbacks on the same type of event.