DEV Community

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

 
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 πŸ˜„