How to use axios to filter multiple repeated requests in a project

How to use axios to filter multiple repeated requests in a project

1. Introduction:

In the process of web application development, we often encounter scenarios where multiple requests are initiated at one time.

In this case, we usually have two approaches:

  • You can show a loading screen when requesting to prevent user operation.
  • Or add a variable manually to throttle a request

In our projects, the above two methods are currently used in most cases. Today I’d like to introduce a new method.

2. CancelToken Class

We previously instantiated a Promise. Whether this object is successful or not cannot be determined outside the function. Here we need to use a little trick to separate a promise from its resolution. Resolve can be triggered at any time:

  // a promise
  let resolvePromise
  let p = new Promise((resolve, reject) => {
    resolvePromise = resolve
  })
  // This executes resolvePromise() externally

Ok, with this premise, we need to use the axios.CancelToken class.

This class is equivalent to opening another promise at each request and forming a promise.race (request p1, cancel request p2). The resolve method in the promise is assigned to an external variable to receive. We can manually decide whether to cancel the previous request based on demand. In fact, this is similar to the Promise.race that we wrote when the fetch encapsulation interface timed out.

cancelToken also provides a corresponding static method source to generate a cancelToken and a cancel method, which is actually a resolve of this promise.

    CancelToken.source = function source() {
    var cancel;
    // 
    var token = new CancelToken(function executor(c) {
        cancel = c;
    });
    return {
        token: token,
        cancel: cancel,
    };

According to our common caching method, we can declare a map to store the URL of each request and the corresponding cancel method.

    //Declare a global map
    const pendingHttp = new Map()
    // CancelToken class built into axios const CancelToken = axios.CancelToken
       
    function addApi (config) {
      config.cancelToken = new CancelToken((cancel) => {
        const url = config.url
        console.log(pendingHttp)
        if (!pendingHttp.has(url)) {
          pendingHttp.set(url, cancel)
        }
      })
    }

    function cancelApi (config) {
      const url = config.url
      if (pendingHttp.has(url)) { // If the current request identifier exists in pending, you need to cancel the current request and remove const cancel = pendingHttp.get(url)
        cancel(url + 'cancelled')
        pendingHttp.delete(url) // Clear the cache of the current url}
    }
  • Pay special attention that if you want to cancel a request, you need to add the cancelToken attribute to the config and assign it to an instance of CancelToken. Otherwise the cancel cannot be done.

Just like operating a timer, try to cancel the previous one before starting the next one.

    httpService.interceptors.request.use(config => {

      cancelApi(config)
      addApi(config)
      
      // When debugging locally, it is a cross-domain situation, and adding a request header will have restrictions (the project code here is irrelevant)
      const { headers = {} } = config; const { globalObj = {} } = window
      Object.assign(headers, globalObj, { from })
      
      return config
    }, error => {
      console.log(error)
      return Promise.reject(error)
    })

Then there is another possibility that the first request has returned and the same request is initiated again, so cancelApi is also required in the response.

    httpService.interceptors.response.use(
      response => {
        cancelApi(response.config)
        sentryCatchApi(response)
      },
      error => {
        // Request timeoutif (error.message.includes('timeout')) { // Determine whether the request exception information contains the timeout string Toast.error({ text: 'Webpage request timeout, please refresh and try again~' })
        }
        sentryCatchApi(error)
        return Promise.reject(error)
      }
    )

We need to note that cancel is actually resolve. The parameters passed in when we cancel the execution will eventually be returned as parameters in the error callback of the response, so our error capture method may report an error.

    // Assume that our error method is encapsulated like this. Let's take a look at sentryCatchApi
    error => {
      sentryCatchApi(error)
      return Promise.reject(error)
    }
  // Because this method needs to receive an object, but when we cancel the request, a string is returned, and an error is reported.
  function sentryCatchApi (res) {
      try {
        res = res || {}
        const resData = res.data || {}
        Sentry.captureException(JSON.stringify(resData))
        console.log(`
          Failed to obtain data:
          Please open the address of webview in the browser and paste it out to facilitate troubleshooting: Interface related information:
          Interface address: ${res.config.url},
          Interface return value: code: ${resData.code},
          message:${resData.message},
          data:${JSON.stringify(resData.data)}
        `)
      } catch (err) {
        console.error(err)
      }
    }

Need to use the isCancel api

   error => {
    if (axios.isCancel(error)) return console.log('The request was canceled', error.message)
    sentryCatchApi(error)
    return Promise.reject(error)
  }

Final result

There is no error in the console. (To be improved in the project later)

Summarize

This is the end of this article about how to use axios to filter repeated requests in a project. For more information about axios filtering repeated requests, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Axios cancel request and avoid duplicate requests
  • Axios cancels repeated requests
  • How to cancel repeated and useless requests in axios
  • Vue axios repeated click cancel the last request encapsulation method
  • A brief discussion on Axios's solution to remove duplicate requests

<<:  Problems encountered in the execution order of AND and OR in SQL statements

>>:  A detailed introduction to the three installation methods of rpm, yum and source code under Linux

Recommend

How to change apt-get source in Ubuntu 18.04

When using apt-get to install, it will be very sl...

Summary of Linux vi command knowledge points and usage

Detailed explanation of Linux vi command The vi e...

Sample code for implementing follow ads with JavaScript

Floating ads are a very common form of advertisin...

Example of using store in vue3 to record scroll position

Table of contents Overall Effect Listen for conta...

Implementation example of Nginx+Tomcat load balancing cluster

Table of contents introduction 1. Case Overview 2...

Mybatis mysql delete in operation can only delete the first data method

Bugs As shown in the figure, I started to copy th...

A detailed analysis of the murder caused by a misplaced double quote in MySQL

1. Introduction Recently, I often encounter devel...

The difference between this.$router and this.$route in Vue and the push() method

The official document states: By injecting the ro...

Sample code for implementing the Olympic rings with pure HTML+CSS

Rendering Code - Take the blue and yellow rings a...

Detailed explanation of simple snow effect example using JS

Table of contents Preface Main implementation cod...

HTML structured implementation method

DIV+css structure Are you learning CSS layout? Sti...