Please take a look at the following code, do you think which log will be printed first?
In Chrome & IE, “sync ajax call: success” is showed first which is expected,
BUT in FF(tested in FF 3.6 & FF 17.0), “async ajax call: success” is showed first instead,
which means although we make the second one as a sychronous call, but when its onreadystatechange was triggered, the handler of asychronous(first) ajax call was executed earliar than that of sychronous(second) ajax call, does it make sense?
Isn’t it a firefox bug?
// first ajax call, Note: this is asynchronous.
$.ajax({
url: "/rest/someUrl",
async : true,
dataType : "json",
contentType: "application/json",
success : function(data) {
console.log("async ajax call: success");
},
error : function(data) {
}
})
// second ajax call, Note: this is synchronous.
$.ajax({
url: "/rest/someUrl",
async : false,
dataType : "json",
contentType: "application/json",
success : function(data) {
console.log("sync ajax call: success");
},
error : function(data) {
}
})
to implement something “correctly” , there must be some specification.
Inside the specification I haven’t found any reference to the fact that all scripts should stop executing as long as the synchronous request isn’t finished(note that the async-XHR is already running when the sync-XHR starts).
But I found this:
Each XMLHttpRequest object has its own task source. Namely, the XMLHttpRequest task source.
—both requests represent a single task-source—
When a user agent is to queue a task, it must add the given task to one of the task queues of the relevant event loop. […] tasks from different task sources may be placed in different task queues.
—both tasks may be added to the same task-queue, but must not—
An event loop must continually run through the following steps for as long as it exists:
1.Run the oldest task on one of the event loop’s task queues, if any, […]. The user agent may pick any task queue.
—he picks now the task-queue where he puts on the synchronous request
When I not misunderstood this, and my logic is not wrong, this could be going on:
Firefox puts both XHR on the same queue, IE and chrome put them onto different task-queues.
All browsers run now the task-queue where they placed the synchronous XHR.
Both implementations seem to be correct.