Reputation: 482
I'm stuck. This makes no sense.
This following line of code calls loadJSONfile, and then sets up a call to dataLoaded when the getJSON resolves.
$.when(loadJSONfile(pathToLoad + "/" + fileToLoad,provIdx)).done(dataLoaded);
Here's loadJSONfile:
function loadJSONfile(pathToFile,idx1,idx2,num2,idx3,num3,dir) {
var deferred = $.Deferred();
//var IDX = idx;
/* code to load the stuff goes here */
$.getJSON(pathToFile).done(function(data) {
deferred.resolve(data,idx1,idx2,num2,idx3,num3,dir);
}).fail(function() { console.log('FAILED') });
return deferred.promise();
}
The following line of code calls loadMapData, and sets up a call to mapDataLoaded wheen loadMapData resolves:
$.when(loadMapData(provinceEntry,regionIdx)).done(mapDataLoaded);
Here's loadMapData:
function loadMapData(provinceEntry,regionIdx) {
var deferred = $.Deferred();
var regionCode = provinceEntry.regions[regionIdx];
$.getJSON('data/topojson' + String(provinceEntry.Number) + String(regionCode) + '.topojson').done(function(topoData) {
deferred.resolve(topoData,provinceEntry,regionIdx);
})
}
But it doesn't work. The code resovles the deferred instantly, which obviously causes mapDataLoaded to fail.
Why does one work when the other, which is identical, not work?
Upvotes: 0
Views: 72
Reputation: 707218
loadMapData()
is not returning anything. It must return a promise for $.when()
to do its job like you are doing in loadJSONfile()
.
But, I must say, you're using some anti-patterns for promises (creating new promises when you don't need to).
Here's a fixed loadMapData()
without the anti-patterns and returning a promise:
function loadMapData(provinceEntry,regionIdx) {
var regionCode = provinceEntry.regions[regionIdx];
return $.getJSON('data/topojson' + provinceEntry.Number + regionCode + '.topojson');
}
loadMapData(provinceEntry,regionIdx).then(function(topoData) {
// you can refer to topoData, provinceEntry and regionIdx here
mapDataLoaded(topoData, provinceEntry,regionIdx);
}, function(err) {
// error handling here
});
The key to avoiding the anti-pattern is to avoid creating a new promise when $.getJSON()
already returns one so you just use the promise that is already being returned.
And, a word about $.when()
. First off, you MUST pass it one or more promises. It has no magic power to know when some async function you pass it is actually done. It only knows how to use promises. And, secondly, there is zero reason to use $.when()
unless you are trying to coordinate more than one promise. If you have just a single promise, you can just use .then()
on the promise itself (like I did on the loadMapData()
above - there's no need to wrap it in $.when()
.
Upvotes: 1