Reputation: 196
I have code retrieving some data using an XMLHttpRequest
that looks something like this:
var myObject = new MyObject();
var req = new XMLHttpRequest();
req.addEventListener("load", function () {
myObject.data = req.responseText;
}, false);
req.addEventListener("loadend", function () {
myObject.save();
}, false);
req.open("GET", "http://www.example.com/foo.txt", true);
req.send(null);
Basically, if the Ajax request succeeds, I want to save the data retrieved in myObject
, and then regardless of the status of the Ajax request, I want to save myObject
to the database. So far it's worked as it's intended to, but I'm slightly uneasy about the order of execution of the load
and loadend
listeners. The most I could find on this was from the XMLHttpRequest
living standard (regarding loadend
):
After one of error, abort, timeout or load has been dispatched.
Does this guarantee that if the Ajax request succeeds, that the load
listener will finish executing before the loadend
listener starts?
Upvotes: 2
Views: 2840
Reputation: 664971
order of execution of the
load
andloadend
listeners
As you can judge from the standard, loadend
will always be dispatched after load
or the respective error event.
Does this guarantee that if the Ajax request succeeds, that the
load
listener will finish executing before theloadend
listener starts?
JavaScript is single-threaded, with a run-to-completion event loop. Two listeners will never run at the same time.
Upvotes: 3