Is there a way to create a loop with a repeated .then
clause? I need to continue executing the .then clause promise, and if the exit condition is not met, I have to repeat the same process until the condition is satisfied.
My scenario involves making multiple ajax GET requests for different "pages" of data until all the required data is fetched.
To simplify, here is an example of the .then clause that I wish to implement as .thenRepeat
:
.then(function(retData) {
namesList.push.apply(namesList, retData); // merge data into list
queryParms.pageNo++; // move to next page
return pretendAjaxFnc(queryParms); // fetch next page
})
Here is a runnable demonstration:
function pretendAjaxFnc(obj) {
return Promise.resolve().then(function() {
if (obj.pageNo < 6) { // define an imaginary "stop iterating" point.
// provide some dummy records
return [{ fld1: "data1", fld2: "data2" },
{ fld1: "data1", fld2: "data2" }];
} else {
// this serves as the exit condition
// It will eventually result in a custom exception from a 404 http status
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); // add data to list
queryParms.pageNo++;
console.log("EIC.GTEST11 list.len: ", namesList.length);
return pretendAjaxFnc(queryParms);
})
// keep repeating until an exit criteria is reached - such as an exception
.then(function(retData) {
namesList.push.apply(namesList, retData);
queryParms.pageNo++;
console.log("EIC.GTEST21 list.len: ", namesList.length);
return pretendAjaxFnc(queryParms);
})
// keep repeating until an exit criteria is reached - such as an exception
.then(function(retData) {
namesList.push.apply(namesList, retData);
queryParms.pageNo++;
console.log("EIC.GTEST31 list.len: ", namesList.length);
return pretendAjaxFnc(queryParms);
})
// keep repeating until an exit criteria is reached - such as an exception
// ...
.catch(function(ex) {
if (ex.message === "NO-MORE-DATA") {
return namesList;
} else {
throw ex;
}
});
};
clientAccumulator(); // Execute the function
This code is intended for execution on current iOS/Safari & Firefox browsers (with additional variations preferred). AngularJS is used, however, I have attempted to remove any specific references.
I am seeking advice or guidance on implementing a .thenRepeat
functionality. Can anyone assist?