Send multiple http request via parse.cloud.httpReq

2019-09-02 22:31发布

I'm trying to send multiple HTTP Requests via Parse.Cloud.httpRequest but I get

{"code":141,"message":"Error: Can't call success/error multiple times

I need to do all requests and put results in " responses " and return responses back so I can use it in another function.

OR maybe I'm in the wrong direction if anyone could guide me.

Regards

Parse.Cloud.define('http', function(request, response) {

var query = new Parse.Query(Parse.Installation);
var responses = new Array ();

for (var i = 0; i < request.params['params'].length; i++) {
      var object = request.params['params'][i];

      Parse.Cloud.httpRequest({
          url: 'http://185.xxxxxxx'+ object +'&languagePath=en',
          success: function(httpResponse) {
            responses.push(httpResponse);
          }
        }).then(function(httpResponse) {
          console.log('Request Succeeded with response Data ' + httpResponse.text);
          response.success(responses);
        },function(error) {
          // error
          console.error('Request failed with response code ' + httpResponse.status);
        }); 
    }
});

1条回答
女痞
2楼-- · 2019-09-02 23:13

The trick is to collect promises to complete the http requests, then set the response "when" the promises are complete.

Parse.Cloud.define('http', function(request, response) {
    var promises = [];

    for (var i = 0; i < request.params['params'].length; i++) {
        var object = request.params['params'][i];
        promises.push(makeRequestWithObject(object));
    }
    Parse.Promise.when(promises).then(function() {
        // results are passed to this function as var args
        response.success(arguments);
    }, function(error) {
        response.error(error);
    });
});

// return a promise to complete an http request with object
function makeRequestWithObject(object) {
    var url = 'http://185.xxxxxxx'+ object +'&languagePath=en';
    return Parse.Cloud.httpRequest({ url:url });
}
查看更多
登录 后发表回答