Last active
January 24, 2018 16:14
-
-
Save briancribb/6ba6906e8b1e813f82c2a8e41d079273 to your computer and use it in GitHub Desktop.
Deferred Example with Multiple Sources
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function getData() { | |
// Fiddle example here: https://jsfiddle.net/briancribb/1j9kdy2q/ | |
// Using an array of data sources, so we can add or subtract them later if we want to. | |
var that = this, | |
dfd_array = [], | |
dfd_sources = { | |
FIRST : { path:'path/to/data/stuff.json'}, | |
SECOND : { path:'path/to/data/stuff.json'} | |
}, | |
objData = { | |
count : 0 | |
}; // We're eventually going to dump all of our data into this object. | |
// Each source is an object, so we can add more properties to it, like its own Deferred. | |
$.each( dfd_sources, function( key, value ) { | |
/* | |
The key and value are just from the items in the sources array above. The key is the name of the source, | |
and the value is the object with the path in it. | |
key: 'FIRST' | |
value: { path:'path/to/data/stuff.json'} | |
*/ | |
value.dfd = $.Deferred(); // Adding a Deferred to the source object. | |
dfd_array.push(value.dfd); // Adding the whole object to the array that we're going to use with AJAX. | |
/* | |
This done() function will fire whenever this deferred object is resolved. It's made in the scope of this | |
function, so we don't need to specifically name it. We have access to the value object, though, so code | |
could be written to target something by name. | |
*/ | |
value.dfd.done(function(singleData) { | |
// Do stuff when this particular deferred resolves. Like increment the count. | |
objData.count ++; | |
// Add this one's data to the main object with the key as the property name so we can see it later. | |
objData[key] = value; | |
/* | |
Logging an array so we can see the string and pass in the single data. | |
(•_•) | |
<) )╯ All the single data! | |
/ \ | |
*/ | |
console.log( [ ('This Deferred has resolved. Count is ' + objData.count) , singleData ] ); | |
}); | |
$.ajax({ | |
url: value.path, | |
dataType: "json" | |
}).done(function(data) { | |
//All done with this JSON file, so we'll resolve its Deferred object. and pass in its data. | |
value.dfd.resolve(data); | |
}); | |
}); | |
/* http://stackoverflow.com/questions/5627284/pass-in-an-array-of-deferreds-to-when */ | |
$.when.apply(null, dfd_array).done(function() { | |
console.log( [ ('All of the ajax calls are complete. Final Count is ' + objData.count) , objData ] ); | |
}); | |
}// End of _getData() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment