I have an array of files. I want to read all of them and make a json array out of it. The problem is that d3.csv
is an asynchronous function.
From this question, I have come to know that $q.defer()
has to be used to returned deferred promise to the controller.
My problem is that I have to read an array of files and make corresponding array of objects.
Here is the code so far:
myApp.factory('myFactory', function($q) {
var masterData=[];
var visFolder = "/data/";
var files=[(visFolder + "Crime_full1.csv"),(visFolder + "accidents.csv"),(visFolder + "health.csv")];
return {
// Get all masterData
get: function() {
var deferred = $q.defer();
//I want to read all the files in array
d3.csv(files[0], function(d) {
masterData.push(d);
deferred.resolve(masterData);
console.log("a csv file read");
});
return deferred.promise;
}
}
});
myApp.controller('visCtrl', function($scope, $routeParams,myFactory) {
myFactory.get().then(function(masterData) {
//masterdata should contain data of all the files in an array
$scope.masterData = masterData;
});
});