原生ajax封装成Promise

代码:

    function myAjax(method,url,params){
        this.state = 'FULFILLED'
        this.fulfillList = []
        this.rejectList = []
        (function(that){
            var data = null
            method = method.toUpperCase()
            if(typeof params == 'object'){
                var _arr = []
                for(var item in params){
                    _arr.push(item+"="+params[item])
                }
                params = _arr.join('&')
            }
            if(method === 'GET'){
                url +='?'+params
            }
            if(method === 'POST'){
                data = params
            }
            //start
            var xhr = new XMLHttpRequest()
            xhr.open(method,url)
            xhr.setRequestHeader('Content-type','appliction/x-www-form-urlencoded')
            xhr.addEventListener('readystatechange',function(){
                if(this.readyState !== 4)return;
                if(this.status !== 200)
                    reject({status:this.status,statusText:this.statusText})
                else
                    resolve(this.responseText)
            })
            xhr.send(data)
            //成功
            var resolve = function(data){
                that.state = 'FULFILLED'
                setTimeout(function () {
                    that.fulfillList.forEach(function (itemFn,key,arr) {
                        itemFn(data)
                        arr.shift()
                    })
                },0)
            }
            //失败,执行失败队列的函数
            var reject = function(data){
                that.state = 'REJECTED'
                setTimeout(function () {
                    that.rejectList.forEach(function (itemFn,key,arr) {
                        itemFn(data)
                        arr.shift()
                    })
                },0)
            }
        })(this)
    }

    
    //成功回调函数
    myAjax.prototype.done = function(handle){
        if(typeof handle === 'function')
            this.fulfillList.push(handle)
        else
            throw new Error('回调函数出错')
        return this
    }
    //失败回调函数
    myAjax.prototype.fail = function(handle){
        if(typeof handle === 'function')
            this.rejectList.push(handle)
        else
            throw new Error('回调函数出错')
        return this
    }
    //失败成功写在一个方法内
    myAjax.prototype.then = function(fulfill,reject){
        this.done(fulfill||function () {})
        .fail(reject)||function () {}
        return this
    }

    //测试ajax
    var ajax = new myAjax('get','./time.php',{a:'123'})

    ajax.then(function(data){
        console.log(data)
    },function(data){
        console.log(data)
    })

写的myAjax函数里面包裹了一个自执行的函数,函数里面对数据处理然后创建XMLHttpRequest对数据进行发送,然后用resolve,reject,函数处理返回结果,给resolve,reject函数添加setTimeout函数,成为异步函数。
添加原型方法处理回调把成功失败函数放进队列。

你可能感兴趣的:(js)