In a NodeJs backend, I need to implement a function which tries for 10 times max to retrieve the data from a request.
The retry need to be waiting for 15s before hit again the request.
If on the first try the request succeed I have to return the data.
If it fails it is retiring 10 times and after that on the 10th time fails, has to return null.
My issue is with following function:
// Helper for the waiting
const sleep = (ms) => {
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
};
async function getData(documentId, log) {
const MAX_RETRIES = 10;
const timeout = 15000;
for (let i = 0; i <= MAX_RETRIES; i += 1) {
try {
const { icfDocuments } = await request(
CONSENT_SERVICE_URL,
getICFDocumentRecipientsQuery,
{
documentId,
}
);
// if the pdfUrl is present return the data
if (icfDocuments.nodes[0].revision.pdfUrl) return icfDocuments;
} catch (err) {
log.debug('Waiting for retrieve the last revision pdfUrl', timeout, 'ms');
await sleep(timeout);
log.debug('Retrying', err.message, i);
}
}
// What here ??? return data or null ???
return null;
}
What I need to wait is that pdfUrl to be present in the data. Not to be null.
If it is null than should be retry max 10 times to see if we get that pdfUrl.
If that fails I return null.
If that success I return the data.
At the moment this above not really work and not sure how to make it correct to get the right output.