DEV Community

Abhishek Gupta
Abhishek Gupta

Posted on

2 2

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

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay