1

I am writing a simple app where I need to get the data from a http get api call and store it in Parse for some reason not all the data is stored. Also the http call returns before saving all the data here is the code.

How can I make it to return only after saving all the data?

Parse.Cloud.httpRequest({
    url: 'http://api.rottentomatoes.com/api/public/v1.0/lists/movies/upcoming.json?apikey=apikey',
    success: function(httpResponse) {


      var jsonobj = JSON.parse(httpResponse.text);

      var total = jsonobj.movies.length;

      for ( var idx in jsonobj.movies) {
        var movie = new Movie();
        movie.save(new Movie(jsonobj.movies[idx])).then(
          function(object){
            console.log(object)
          },
          function(error){
            console.log(error);
          }
        )

      }
      response.send("All saved");

    },
    error: function(httpResponse) {
      console.error('Request failed with response code ' + httpResponse.status);
      response.send("Failed");
    }
})
Shrikar
  • 840
  • 1
  • 8
  • 30

1 Answers1

1

You need to aggregate all the promises you used via an aggregation function, in the case of parse promises, it's .when :

Parse.Cloud.httpRequest({
    url: 'http://api.rottentomatoes.com/api/public/v1.0/lists/movies/upcoming.json?apikey=apikey',
    success: function(httpResponse) {


      var jsonobj = JSON.parse(httpResponse.text);

      var total = jsonobj.movies.length;
      var results = [];
      // do NOT iterate arrays with `for... in loops`
      for(var i = 0; i < jsonobj.movies.length; i++){
          var movie = new Movie();
          results.push(movie.save(new Movie(jsonobj.movies[i]))); // add to aggregate
      }
      // .when waits for all promises
      Parse.Promise.when(promises).then(function(data){
           response.send("All saved");
      });


    },
    error: function(httpResponse) {
      console.error('Request failed with response code ' + httpResponse.status);
      response.send("Failed");
    }
})

Although, it might be better to use promises for the httpRequest too, this should work.

Benjamin Gruenbaum
  • 270,886
  • 87
  • 504
  • 504
  • I am getting this error {"code":111,"message":"invalid type for key runtime, expected number, but got string"} – Shrikar May 14 '14 at 16:33
  • I also checked the docs for parallel promises https://parse.com/docs/js_guide#promises . – Shrikar May 14 '14 at 16:34
  • 1
    This error has nothing to do with promises, your Parse objects are not defined well, you're passing it a string where it expects a number, try passing it `+jsonobj.movies[i]` or something similar. It's a data integrity issue that's unrelated to your actual question here, use the debugger to step through and find the offending line. – Benjamin Gruenbaum May 14 '14 at 16:35
  • you also mentioned // do NOT iterate arrays with `for... in loops` what is the reason for that? – Shrikar May 14 '14 at 16:41