Created
May 4, 2021 02:16 PM
Description
Last Edited
Jan 27, 2022 06:36 AM
Tags
Front-end
Code
const poll = async ({ fn, validate, interval, maxAttempts }) => { let attempts = 0; const executePoll = async (resolve, reject) => { const result = await fn(); attempts++; if (validate(result)) { return resolve(result); } else if (maxAttempts && attempts === maxAttempts) { return reject(new Error('Exceeded max attempts')); } else { setTimeout(executePoll, interval, resolve, reject); } }; return new Promise(executePoll); };
Arguments
fn
: This is the function we will execute over a given interval. Typically this will be an API request.
validate
: This is also a function where we define a test to see if the data matches what we want which will end the poll. For example, we can simply test if the data exists or we could check if a nested property of the response has reached a certain state
Ex.
validate = user => !!user
Ex.
validate = checkout => checkout.status === 'COMPLETE'
interval
: This is the time we want to wait between poll requests. This is entirely determined by the use case in your app, and the higher the importance of having the most up to date information, the shorter the interval will need to be between poll requests.
maxAttempts
: We need the ability to set some reasonable upper bound for the number of poll requests to be able to prevent it from running infinitely.