How can I repeat a .then
clause as a loop? I need to wait for the .then clause promise to resolve, and then if the exit criteria has not been met, I need to repeat the same operation again ... until the exit criteria is met.
My use case is a repeating ajax GET call for multiple "pages" of data until all the data has been retrieved.
I can simplify and simulate the issue as follows. This is the .then clause that I would love to .thenRepeat
:
.then(function(retData) {
namesList.push.apply(namesList, retData); // accum data into list
queryParms.pageNo++; // set to next page
return pretendAjaxFnc(queryParms); // get next page
})
And this is a runnable example:
function pretendAjaxFnc(obj) {
return Promise.resolve().then(function() {
if (obj.pageNo < 6) { // create a pretend "I'm done" point.
// return a couple dummy records
return [{ fld1: "data1", fld2: "data2" },
{ fld1: "data1", fld2: "data2" }];
} else {
// this is the exit criteria
// It will actually be 404 http status converted to a custom exception
throw new Error("NO-MORE-DATA");
}
});
};
function clientAccumulator() {
var namesList = [];
var queryParms = {
pageNo: 1
};
return pretendAjaxFnc(queryParms)
.then(function(retData) {
namesList.push.apply(namesList, retData); // append data to list
queryParms.pageNo++; // set to get next page
console.log("EIC.GTEST11 list.len: ", namesList.length);
return pretendAjaxFnc(queryParms);
})
// repeat until some exit criteria - like an exception
.then(function(retData) {
namesList.push.apply(namesList, retData);
queryParms.pageNo++;
console.log("EIC.GTEST21 list.len: ", namesList.length);
return pretendAjaxFnc(queryParms);
})
// repeat until some exit criteria - like an exception
.then(function(retData) {
namesList.push.apply(namesList, retData);
queryParms.pageNo++;
console.log("EIC.GTEST31 list.len: ", namesList.length);
return pretendAjaxFnc(queryParms);
})
// repeat until some exit criteria - like an exception
// ...
.catch(function(ex) {
if (ex.message === "NO-MORE-DATA") {
return namesList;
} else {
throw ex;
}
});
};
clientAccumulator(); // Run the function
This is Browser code that needs to run on current iOS/Safari & Firefox (though preferably more variations). I'm using AngularJS, but I believe I've removed any of that specificity.
Does anyone have a .thenRepeat
they can point me to?