ES6中Promise封裝ajax的寫法


1.依賴jquery的寫法可以使用下面的
    (function($){
        $.extend({
            ajaxPromise:  param => {
                return new Promise((resolve, reject) => {
                    $.ajax({
                        method: param.method || "GET",
                        dataType: "JSON",
                        url: param.url,
                        data: param.data || "",
                        success: res => {
                            if (res.status == 1) {
                                resolve(res.data);
                            }
                            else if (res.status == -1001) {
                                console.log("需要登錄");
                            }
                        },
                        error: err => {
                            if (err.status == 404) {
                                console.log("404");
                            } else {
                                reject(err);
                            }
                        }
                    })
                })
            }
        })
    })(jQuery);

 

2.如果不依賴jquery可以采用下面的寫法

const ajaxPromise =  param => {
        return new Promise((resolve, reject) => {
            $.ajax({
                type: param.type || "get",
                url: param.url,
                data: param.data || "",
                success: res => {
                    if(res.status == 1){
                        resolve(res.data);
                    }
                    else if(res.status == -1001){
                        alert("需要登錄");
                    }else{

                    }
                },
                error: err => {
                    if(err.status == 404){
                        alert("404");
                    }else{
                        reject(err);
                    }
                }
            })
        })
    };

  

使用jquery示例

  /*
     第一個請求
     */
    let step1 = () => {
        $.ajaxPromise({
            url:"agents/get/2068957732939648",
            data: {
                "token":"f59e423eb75503f5609a0b9ba3b38db8083ad65078edb945b4c528fe6440b728"
            }
        }).then(res => {
            console.log("第一個請求正確返回==>"+res);
        }).catch(err => {
            console.log("第一個請求失敗",err);
        })
    };

    /*
     第二個請求
     */
    let step2 = () => {
        $.ajaxPromise({
            url:"http://staging.santezjy.com:1031/agents/get/2068957732939648",
            data: {
                "token":"f59e423eb75503f5609a0b9ba3b38db8083ad65078edb945b4c528fe6440b728"
            }
        }).then(res => {
            console.log("第二個請求正確返回==>",res);
        }).catch(err => {
            console.log("第二個請求失敗==>"+err);
        })
    };

    step1();
    step2();

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM