According to jQuery docs:
To execute a function after two ajax requests are successful:
$.when($.ajax("/page1.php"), $.ajax("/page2.php")).done(function(a1, a2){
/* a1 and a2 are arguments resolved for the
page1 and page2 ajax requests, respectively */
var jqXHR = a1[2]; /* arguments are [ "success", statusText, jqXHR ] */
if ( /Whip It/.test(jqXHR.responseText) ) {
alert("First page has 'Whip It' somewhere.");
}
});
I have this:
$.when(
file2store('resources/states_obj.txt?v=2', 'states'),
file2store('resources/lgas_obj.txt?v=2', 'lgas'),
file2store('resources/villages_obj.txt?v=2', 'villages'),
file2store('resources/staff_obj.txt?v=2', 'staff')
).done(function(){
console.log('All data put');
});
function file2store(url, store_name){
$.getJSON(url, function(obj){
db.put(store_name, obj).then(
function(ids) {
console.log(store_name+': '+ids.length + ' items put.');
}, function(e) {
throw e;
}
);
});
}
The variable db
in the ajax callback is a global variable for the indexedDB Storage object, obtained (not shown here) at the top of the script.
Is this a correct usage of the jQuery Deferred
construct?
Will the function calls file2store
be queued, meaning, make sure that one call finishes before the next one kicks in?
is this a correct usage of the jQuery Deferred construct?
Not quite. The when()
method accepts the deferred
object, as returned from a jQuery method which creates an AJAX request. As such, you need to return
that object for your code to work:
function file2store(url, store_name){
return $.getJSON(url, function(obj) { // note the return here.
// rest of your code...
});
}
Will the function calls file2store be queued, meaning, make sure that one call finishes before the next one kicks in?
No. They are created in the order you provide them however they will be completed in whatever order the server responds to them.