dimanche 25 janvier 2015

Timing of resolving of promises and handling browser events

Consider the following code written in ES6:



function waitForMessage() {
return new Promise((resolve, reject) => {
function handler(event) {
resolve(event);
window.removeEventListener('message', handler);
};
window.addEventListener('message', handler);
});
}

function loop(event) {
// do something (synchronous) with event
waitForMessage.then(loop);
}
waitForMessage.then(loop);


In this piece of code, waitForMessage installs an event handler waiting for a message to arrive at the current window. Once it has arrived, the promise returned by waitForMessage is being resolved and the event handler removed.


In loop, a new promise is being generated by waitForMessage as soon as the job enqueued by resolving the previous promise is being run.


Now my question is whether loop may not get all messages posted at window due to a timing problem: If the jobs enqueued by Promise.prototype.resolve are not always being run before any tasks enqueued in the browser's event loop, it may be the case that an message event is begin dispatched at window while there is currently no handler listening for this event.


What does the standard say about the timing of these different types of jobs/tasks, namely resolving the callbacks of promises and the dispatching of events from outside of the ES6 world?


(I just took the message event as an example, I am equally interested in other events, like click or popstate events.)





Aucun commentaire:

Enregistrer un commentaire