I'm trying to make a sequential chain of Parse Promises with varying length and Cloud Function parameters like this:
var anArray = ['1', '2'];
var promise = new Parse.Promise.as();
for (var i = 0; i < anArray.length; i++) {
promise = promise.then(
function() {
return Parse.Cloud.run('cloudFunc', {arg: anArray[i]});
}
)
}
promise.then(
function(result) {
// print result of last promise
}
);
Parse.Cloud.define('cloudFunc', function(request, response) {
response.success(request.params.arg);
});
This works well if the array only contains one element, however all subsequent Cloud Function calls is made with arg = undefined. Is there a way where I can get the intended functionality?
I suspect i
reaches 2
as the For
loop ends before most of your Cloud calls are resolved which means you are potentially sending anArray[2]
as the parameter and that is clearly undefined. Replace your For
loop with forEach
instead to make sure that you send in the correct element of the array as the parameter for each call:
anArray.forEach(function(element) {
promise = promise.then( function() {
return Parse.Cloud.run('cloudFunc', {arg: element});
});
});