Location>code7788 >text

Implementing cancelable axios requests using js closures

Popularity:408 ℃/2024-09-09 22:33:28

In the usual development, often encounter repeated requests, perhaps because of network problems, perhaps because of interface problems and so on, the traditional practice is that the client uses anti-shaking to limit the frequency of users to send interfaces, generally out of a loading spinning around in the form of a

But the practice of canceling requests is seldom used, and now I'll document how to employ closures to encapsulate a cancelable request function, the first thing you need to understand is that the

1. Closures

2. AbortController()

Without going into the above here, let's go straight to the code:

Note that the instance returned by the AbortController constructor contains the abort function as a one-time use, meaning that an abort instance can only correspond to one xhr request and can only be used once ()

Understanding this, then we can easily implement such a decorator function with the help of closures:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <script src="/axios/dist/"></script>
  </head>
  <body>
    <button id="send">send request</button>

    <script>
      ("send").addEventListener("click", () => {
        getListAbortable()
          .then((res) => {
            ("Data.", res);
          })
          .catch((e) => {
            ("Request Error.", e);
          });
      });

      function AbortRequest(callback) {
        let abortable = null;
        return function () {
          if (abortable) {
            ();
          }
          abortable = new AbortController();
          return callback();
        };
      }

      const getListAbortable = AbortRequest((signal) => {
        return ("/slow", { signal });
      });
    </script>
  </body>
</html>

When I quickly click the button, it automatically cancels the last xhr request and sends the next xhr request until the request is complete.

That's how it's done!