0

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.csvis 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;
  });

});
Community
  • 1
  • 1
vishalaksh
  • 2,054
  • 5
  • 27
  • 45

1 Answers1

1

You have to iterate over the files array and call the function that calls d3 library for each file. This function should return promise. The getFile function below does the same:

getFile = function (file) {
    var deferred = $q.defer();
    d3.csv(file, function (d) {
        deferred.resolve(d);
    });
    return deferred.promise;
}

The getFile function is defined outside the return block. The get function now has to be updated to call getFile with each file and then collate the results with $q.all. The code would look something like this.

get: function () {

    var promises = files.map(function (f) {
        return getFile(f);
    });

    return $q.all(promises).then(function (data) {
        data.forEach(function (f) {
            masterData.push(f);
        });
        return masterData;
    });
}
vishalaksh
  • 2,054
  • 5
  • 27
  • 45
Chandermani
  • 42,589
  • 12
  • 85
  • 88