zoukankan      html  css  js  c++  java
  • axios如何终止多次请求

    一、需求分析

    在项目中经常有一些场景会连续发送多个请求,而异步会导致最后得到的结果不是我们想要的,并且对性能也有非常大的影响。例如一个搜索框,每输入一个字符都要发送一次请求,但输入过快的时候其实前面的请求并没有必要真的发送出去,这时候就需要在发送新请求的时候直接取消上一次请求。

    二、需求实现

    <script>
    import axios from 'axios'
    import qs from 'qs'
    
    export default {
        methods: {
            request(keyword) {
                var that = this;
                var CancelToken = axios.CancelToken
                var source = CancelToken.source()
                  
                // 取消上一次请求
                this.cancelRequest();
                
                axios.post(url, qs.stringify({kw:keyword}), {
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                        'Accept': 'application/json'
                    },
                    cancelToken: new axios.CancelToken(function executor(c) {
                        that.source = c;
                    })
                }).then((res) => {
                    // 在这里处理得到的数据
                    ...
                }).catch((err) => {
                    if (axios.isCancel(err)) {
                        console.log('Rquest canceled', err.message); //请求如果被取消,这里是返回取消的message
                    } else {
                        //handle error
                        console.log(err);
                    }
                })
            },
            cancelRequest(){
                if(typeof this.source ==='function'){
                    this.source('终止请求')
                }
            },
        }
    }
    </script>
    

      注意:

      catch时需要注意拦截判断 ,由于终止也会走catch 所以需要处理

    三、需求实现

    通过这样的操作方法,实现了axios终止多次请求,如图所示:

    在这里插入图片描述

  • 相关阅读:
    Composite in Javascript
    Model Validation in Asp.net MVC
    HttpRuntime.Cache vs. HttpContext.Current.Cache
    Controller Extensibility in ASP.NET MVC
    The Decorator Pattern in Javascript
    The Flyweight Pattern in Javascript
    Model Binding in ASP.NET MVC
    Asp.net MVC
    jQuery Ajax 实例 全解析
    ASP.NET AJAX入门系列
  • 原文地址:https://www.cnblogs.com/lorin/p/14096168.html
Copyright © 2011-2022 走看看