Send multiple http request via parse.cloud.httpReq

天涯浪子 提交于 2019-12-13 05:21:27

问题


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:


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


来源:https://stackoverflow.com/questions/33633083/send-multiple-http-request-via-parse-cloud-httpreq

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!