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");
    }
})
有帮助吗?

解决方案

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top