Perform multiple http calls in a Parse Cloud Function

137 views Asked by At

So, basically I have to call a cloud function hosted on Parse.com that:

  1. perform a first http call
  2. convert the result(json) into a list of objects
  3. do another http call and modify the list of objects with the information provided by the second http call.
  4. return the elaborated json

I've read about Promises here but I can't figure out how I can do something like that..

This is my Main.js file..

Parse.Cloud.define("getSolutions", function(request, response) {

  var _idDepartureStation, _idArrivalStation, _departureTime, _dateTime;
  _idDepartureStation = request.params.idDepartureStation;
  _idArrivalStation = request.params.idArrivalStation;
  _departureTime = request.params.departureTime;
  _dateTime = request.params.dateTime;

  Parse.Cloud.httpRequest({
    url: API_SEARCH_SOLUTION.replace("{IDDEPARTURESTATION}",_idDepartureStation).replace("{IDARRIVALSTATION}",_idArrivalStation).replace("{DEPARTURETIME}",_departureTime)
  }).then(function(httpResponse) {
    // success first call
    console.log("First call");
    return httpResponse.text;
  },function(httpResponse) {
    // error second call
    console.error('Request failed with response code ' + httpResponse.status);
    response.error(httpResponse.status);
  }).then(function(firstResponse){
    // second call
    Parse.Cloud.httpRequest({
      url: API_STATION_STATUS.replace("{IDSTATION}",_idDepartureStation).replace("{TYPE}","partenze").replace("{DATETIME}",_dateTime)
    }).then(function(httpResponse) {
      // success second call
      console.log("Second call");
      return "First: " + firstResponse + "\nSecond: "+httpResponse.text;
    },function(httpResponse) {
      // error second call
      console.error('Request failed with response code ' + httpResponse.status);
      response.error(httpResponse.status);
    })
  }).then(function(result){
    response.success(result);
  });
});

I know that is wrong.. but I've still not clear how Promises works..

From my logs I can see that only "First call" is printed and the result of the function is undefined.

Thanks

0

There are 0 answers