I'm trying to setup a queuing system such that a post request is repeated n
times, at intervals of i
. Ideally I'd like to wrap this all in a single promise, so the whole thing can be asynchronous.
So far I have this, which feels somewhat messy and hacky. I feel like I may be missing a much easier solution, but I can't seem to find anything:
// this is mocked to avoid a wall of code
const postData = (url, data) => Promise.resolve(true);
// this is mocked to avoid a wall of code
const resIsFailed = () => true;
const requestChain = ({
url,
data,
maxRequests,
requestTimeout,
currentRequest = 0,
requestIncrement = increment => increment,
}) => {
// exit condition
if (currentRequest >= maxRequests || (!maxRequests)) {
console.log('Too many failed requests');
return Promise.reject(new Error('Too many attempts'));
}
// post the data, if it fails, try again
postData(
url,
data,
).then(res => {
if (resIsFailed(res)) {
console.log('Failed response: ');
console.dir(res);
setTimeout(() => {
requestChain({
url,
data,
maxRequests,
requestTimeout: requestIncrement(requestTimeout),
currentRequest: currentRequest + 1,
requestIncrement,
});
}, requestTimeout);
} else {
return Promise.resolve(res);
}
});
}
requestChain({
url: 'fail',
data: {},
maxRequests: 5,
requestTimeout: 100,
})