I have the following code which I want to be running asynchronously, but the logs are showing that they are running synchronously.
$(".widget").each(function() {
// snip - url, def, and tempParams defined here
$.ajax({
url: url,
dataType: "jsonp",
type: "POST",
data: {params: tempParams},
success: function(data) {
var st = new Date().getTime();
console.error("Start " + def.name + " @" + st);
doSomething(data);
var et = new Date().getTime();
console.error("End " + def.name + " @" + et);
console.error("Duration " + def.name + " " + (et-st) + " ms.");
}
});
The console output clearly shows the success functions executing in order, rather than asynchronously:
Start f1 @1300738891705
End f1 @1300738891744
Duration f1 39 ms.
Start f2 @1300738892746
End f2 @1300738893280
Duration f2 534 ms.
Start f3 @1300738893282
End f3 @1300738893303
Duration f3 21 ms.
Start f4 @1300738893305
End f4 @1300738893306
Duration f4 1 ms.
Start f5 @1300738893484
End f5 @1300738895609
Duration f5 2125 ms.
Thoughts? I feel like this must be something obvious that I’m overlooking.
I think you’re both confusing the two terms. Asynchronous in terms of AJAX and thus JQuery just means that the HTTP Request message will be sent to the webserver without causing any delay on the client’s end. The requests will more than likely post to the server sequentially, but I don’t think it’s guaranteed. I think you’re thinking in terms of threading…
Synchronous calls may cause delay on the client side while the browser’s javascript interpreter is waiting for the AJAX response.
To think of a quick example, lets say you have an AJAX call that fetches the tax rate given a USA state. If it was a synchronous call, then the checkout tool would stop calculation, and any user interaction with Javascript would not produce a response until the AJAX response (with the tax rate) was received.
In an asynchronous situation from above, you could define a callback function that would continue to calculate the final checkout price once the AJAX response was received.