问题
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