In the work business, due to the continuous request to obtain the current state, I originally considered using WebSocket, but the back end refused to cooperate with it, so I was not satisfied with the online search for axios to find a relatively simple integration solution, so I packaged a simple one based on AXIOS. Quick AXIos polling plugin.

Polling is a process that continues to request the backend interface for a certain period of time, and stops when conditions are specified

Front Desk: Are you ready backstage? (3 seconds later...) Backstage: No. Front Desk: Are you ready backstage? (3 seconds later...) Backstage: No. Front Desk: Are you ready backstage? (3 seconds later...) Backstage: Ok.Copy the code

Of course, it is best to use WebSocket if there are conditions, polling still has many disadvantages.

Axios – polling: TuiMao233 / axios – polling

Blog: tuimao233. Gitee. IO/MAO – Blog /

Use axios – polling

Axios-polling is a simple, fast extension to AXIOS polling that inherits the current AXIOS configuration.

NPM & ESM installation

npm i axios axios-polling
Copy the code

Introduce the use of

import axios from 'axios'
import { axiosPolling } from 'axios-polling'
// initialize axios-polling
axiosPolling(axios, {
  retryLimit: 15
})
// Edit the polling configuration later
axios.defaults.polling['retryLimit'] = 20

// Create a polling request
const { emit, on, off, remove } = axios.poll({
  url: '/message'.params: { id: 1}})// Send a polling request
// The emit configuration is merged with the poll configuration, and the emit configuration takes precedence
emit({ params: { id: 2}})// Listen before sending the request
on('request'.(config) = > {
  console.log(config.polling.count)
})
// Listen after the request is sent
on('response'.(response) = > {
  console.log(response)
})
// Listen request failed
on('error'.(error) = > {
  console.log(response)
})
// Close the polling request
off()
// Remove all on listening queues
remove()
Copy the code

The config configuration

interface AxiosPollingConfig {
  /** Total number of normal polling times. Initial value: 0 */
  count: number
  /** The request delay in normal polling is milliseconds. Default: 1000 milliseconds */
  dalay: number
  /** Poll request interval increments by ms. Default: 0 ms (recommended not to exceed 1000) */
  delayGaps: number
  /** Number of current retries when an error occurred. Initial value: 0 */
  retryCount: number
  /** Maximum number of requests when an error occurs. Default: 10 */
  retryLimit: number
  /** The number of milliseconds to send the request for the first time. Default: 1000 milliseconds */
  retryAfter: number
}
Copy the code