DEV Community

Abhishek Gupta
Abhishek Gupta

Posted on

Poll backend endpoint in Vanilla js

Senario

You need to poll for status of an task until completed. Once it is completed you need to run some js code.

Code

// lib/poll.js
export const timeout = n => new Promise(resolve => setTimeout(resolve, n))

/*
  @fn: (any) => any Function to be executed
  @condition: (res) => Boolean Function to test if we can stop polling
  @maxTries: number Max number of calls allowed before rejection of promise
  @gap: number Minimum time (in ms) between two polls
*/
export const poll = async (fn, condition, maxTries, gap) => {
  while(maxTries--) {
    await timeout(gap)
    const result = await fn()
    if (condition(result)) return result
  }

  throw new Error('Poll Timeout')
}
Enter fullscreen mode Exit fullscreen mode

Usage

const fetchStatus = () => this.$axios.get(`/orders/23222/status`)

poll(fetchStatus, ({status}) => status != 'PENDING', 30, 1000)
  .then(result => console.log(result)) // success!!
  .catch(err => { ... }) // either Timeout or XHR failed with error

Enter fullscreen mode Exit fullscreen mode

Top comments (0)