Promises In Series Are Not Getting Executed In Sequence
Solution 1:
Parse.Cloud.run('sampleCloudFuction', itemsArray, function () {
console.log("success callback in JS");
var tempPromise = Parse.Promise.as();
return tempPromise;
})
That doesn't work. You cannot return
from a callback - the value will just vanish.
However, the docs state that
every asynchronous method in the Parse JavaScript SDK returns a
Promise
- you don't even need to try to construct it on your own!
So, why is the sequential processing not working correctly? Because it requires that the then
callback does return the value of the next step - which can be an asynchronous, not yet resolved promise. Then, the new seriesPromise
will wait for that step before executing the next.
Yet you were not returning anything from that callback - so the then
just resolved the seriesPromise
immediately with undefined
. Return the promise that .run()
yields:
var seriesPromise = newParse.Promise.as();
$.each(items, function (i) {
…
// Series Promise: The code to be executed in sequence being placed within the // then() the existing promise
seriesPromise = seriesPromise.then(function() {
returnParse.Cloud.run('sampleCloudFuction', itemsArray);
// ^^^^^^
});
…
});
seriesPromise.then(function () {
//Fetch the approval state of the disabled buttonalert("load remaining items");
}, function (error) {
alert("Error " + error.code + "::");
console.log("error callback in JS");
});
Solution 2:
var seriesPromise = newParse.Promise.as();
$.each(items, function (i) {
..
..
count++;
if (count >= 25 || (i + 1) >= selectedItemsLength) {
.. ..
// I don't know where you got the understand wrapping code in // Parse.Promise.as() it will executed in series. // from the docs:// Parse.Promise.as()// Returns a new promise that is resolved with a given value.// in fact the following line executed right away and this foreach // function for this item return immediately.
seriesPromise = seriesPromise.then(function () {
Parse.Cloud.run('sampleCloudFuction', itemsArray, function () {
console.log("success callback in JS");
var tempPromise = Parse.Promise.as();
return tempPromise;
}, function (error) {
alert("Error " + error.code + "::");
console.log("error callback in JS")
});
});
count = 0;
}
});
Unfortunately I don't really understand what you trying to do. if your code is too long you can put a jsfiddle.
Post a Comment for "Promises In Series Are Not Getting Executed In Sequence"