DEV Community

Discussion on: Which functions/methods do you...

Collapse
 
joelbonetr profile image
JoelBonetR πŸ₯‡

I'm afraid to ask where you need this one πŸ˜‚πŸ˜‚

Collapse
 
danielfy profile image
Daniel Fyhr

I've used it for polling. And... Sometimes you got to do what you got to do πŸ˜‚

Thread Thread
 
joelbonetr profile image
JoelBonetR πŸ₯‡

Hahaha no judgements. Still I let you some polling thingy I had here that may be more suitable:

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);
};
Enter fullscreen mode Exit fullscreen mode

poll function is a higher-order function that returns a function, executePoll.

executePoll function returns a promise and will run recursively until the condition is met.

Args explained:

fn: an API request (or another async thingy that suits for this polling).

validate: Test function to see if the data matches what we want, in which case it will end the poll.

interval: To specify how much it wait between poll requests.

maxAttempts: how many tries before throwing an error.

😁

Thread Thread
 
rishadomar profile image
Rishad Omar

I couldn't sleep last night and read this comment at 3am. Coincidentally, today, I needed this poll. Works great in my usEffect().
The only thing that caught me is that the parameters to the above poll function are in a class, instead of individual parameters.
Thanks for the code!

Thread Thread
 
joelbonetr profile image
JoelBonetR πŸ₯‡

Didn't get the meaning of the sentence "The only thing that caught me is that the parameters to the above poll function are in a class, instead of individual parameters." still glad to see it helped you 😁

Thread Thread
 
rishadomar profile image
Rishad Omar • Edited

Apologies, I didn't explain correctly.
Initially, I called the poll function incorrectly as follows:

poll(myFunction, myValidate, myInterval, myMaxAttempts)
Enter fullscreen mode Exit fullscreen mode

The correct method (using your code) is:

poll({
   fn: myFunction,
   validate: myValidate,
   interval: myInterval,
   maxAttempts: myMaxAttempts
})
Enter fullscreen mode Exit fullscreen mode
Thread Thread
 
joelbonetr profile image
JoelBonetR πŸ₯‡ • Edited

Oh! nothing to do with classes it's just it receives an object but this is opinionated as I prefer to have the object structure for those "config" thingies, you can simply delete the brackets on the function declaration like that:

const poll = async ( fn, validate, interval, maxAttempts ) => {
Enter fullscreen mode Exit fullscreen mode

and we should be good 😁

Thread Thread
 
alexparra profile image
Alex Parra • Edited

Nice snippet.
The new Promise callback should not be an async function. By passing an async fn to new Promise you’re β€œdouble promising”.
Refactoring to not depend on resolve/reject would solve that.
Or maybe

new Promise((res, rej) => executePoll(res, rej))
Enter fullscreen mode Exit fullscreen mode
Thread Thread
 
joelbonetr profile image
JoelBonetR πŸ₯‡ • Edited

Having it as async lets you handle the response, the error and any action to perform either it went OK or KO, so it can be customised specifically on it's environment.

myPoll.then( res => res ).catch( err => console.error( 'myCustomError', err )).finally( () => setExecutionFinished(true));
Enter fullscreen mode Exit fullscreen mode

instead handling it as generic inside the polling function.

But sure you can tweak it as you wish to fullfill your needs πŸ˜„