I am using promise.js with jQuery but I do not want to use $Deferred as many say it is not accurate or best practice according to Promises/A+.
var promises = [];
var myArray = //something
function readFile(){
$.getJSON( "yyy.com/readfile?callback", function( data ) {
console.log('Reading File');
promises.push(data)
});
}
function writeFile(){
$.getJSON( "yyy.com/writefile?callback", function( data ) {
console.log('Writing File');
promises.push(data)
});
}
for(var i, i < myArray.length, i ++) {
readFile();
writeFile();
}
Promise.all(promises).then(function(){
console.log('ALL DONE!');
// Do something
});
This is the result
All Done!
Reading File
Writing File
Reading File
Writing File
Reading File
Writing File
Something must be wrong with my code. The "All Done" should be log at the last. Can someone guide me in this?
The data returned from your getJSON
calls is most certainly not a promise. From the promisejs site (https://www.promisejs.org/), you can just convert the jQuery promise to a Promise object using:
var jQueryPromise = $.ajax('/data.json');
var realPromise = Promise.resolve(jQueryPromise);
What this will look like in your example is something like the following:
var promises = [];
var myArray = //something
function readFile(){
return Promise.resolve($.getJSON( "yyy.com/readfile?callback", function( data ) {
console.log('Reading File');
}));
}
function writeFile(){
return Promise.resolve($.getJSON( "yyy.com/writefile?callback", function( data ) {
console.log('Writing File');
}));
}
for(var i, i < myArray.length, i ++) {
promises.push(readFile());
promises.push(writeFile());
}
Promise.all(promises).then(function(){
console.log('ALL DONE!');
// Do something
});
Comment update:
If you are wanting your promises to be handled sequentially, you should use .then
, for example:
for(var i, i < myArray.length, i ++) {
var operationPromise = readFile().then(function(readFileResponse){
return writeFile(readFileResponse);
});
promises.push(operationPromise);
}