I have used this common polling function for running background jobs.
export const poll = ({ fn = () => {}, validate = (result) => !!result, interval = 1000, maxAttempts = 15,}) => { let attempts = 1; // eslint-disable-next-line consistent-return const executePoll = async (resolve, reject) => { try { const result = await fn(); attempts += 1; if (validate(result)) { return resolve(result); } else if (maxAttempts && attempts > maxAttempts) { // eslint-disable-line no-else-return return reject(new Error('Exceeded max attempts')); } else { setTimeout(executePoll, interval, resolve, reject); } } catch (error) { setTimeout(executePoll, interval, resolve, reject); } }; return new Promise(executePoll);};
I have called this function on click of a button for running polling:
poll({ fn: () => some API call ex. api.get(url), validate: (res) => !res?.data?.lesson_id, interval: 5000, maxAttempts: 30, })
The issue is that after running the above function in the UI, I am showing a delete icon. On clicking that delete icon, I am removing the element for which the above background job is running.
So I want to stop the above polling function after successful deletion.
Note: I have the delete function on that same page so I have control over delete when it is successful.
What can I change in my common polling function?