I'm looking for a solid answer on whether the following JavaScript code contains a race condition or not.
The question boils down to this: If I begin listening for the completion of an asynchronous task (such as an AJAX call) immediately after I've initiated the task, could that task complete before I've started listening?
I've found a few similar questions, but none has an answer that seems totally concrete ("there could be a problem ... it is unlikely that..."). Here's a rough example of the kind of situation I'm referring to:
// Publish an event synchronously
function emit(key){}
// Subscribe to an event
function on(key, cb){}
// Request the given url;
// emit 'loaded' when done
function get(url) {
http.get(url, function() {
emit('loaded');
});
}
get(url);
on('loaded', function() {
// Assuming this subscription happens
// within the same execution flow as
// the call to `get()`, could 'loaded'
// ever fire beforehand?
});
Even better if the answer has backing from the actual language specification (or another definitive source)!