promise

let

promise_第1张图片
image.png

封装一个jQuery.ajax

可用jQuery.ajax(url,method,body,success, fail)形式使用

 jQuery.ajax= function fn (url, method, body, successfn, failfn) {
    let request = new XMLHttpRequest();
    request.open(method, url);
    request.onreadystatechange = ()=>{
        console.log(request.readyState)
        if(request.readyState === 4){
            if(request.status >= 200){
                successfn.call(undefined, request.responseText)
            } else if (request.status >= 400){
                failfn.call(undefined,request)
            }
        }
    }
    request.send(body)
}

升级你的 jQuery.ajax 满足 Promise 规则

  jQuery.ajax= ({url, method, body})=>{
    return new Promise(function(resolve, reject){
        let request = new XMLHttpRequest();
        request.open(method, url);
        request.onreadystatechange = ()=>{
            console.log(request.readyState)
            if(request.readyState === 4){
                if(request.status >= 200){
                    resolve.call(undefined, request.responseText)
                } else if (request.status >= 400){
                    reject.call(undefined,request)
                }
            }
        }
        request.send(body)
    })
}
let promise = jQuery.ajax(
    {
        url:'/xxx',
        method: 'get',
        body: 'a=1'
    }
)
promise.then(()=>{console.log('succuss')},
()=>{console.log('failed')})

executor是带有 resolve 和 reject 两个参数的函数 。Promise构造函数执行时立即调用executor 函数, resolve 和 reject 两个函数作为参数传递给executor(executor 函数在Promise构造函数返回所建promise实例对象前被调用)。resolve 和 reject 函数被调用时,分别将promise的状态改为fulfilled(完成)或rejected(失败)。executor 内部通常会执行一些异步操作,一旦异步操作执行完毕(可能成功/失败),要么调用resolve函数来将promise状态改成fulfilled,要么调用reject 函数将promise的状态改为rejected。如果在executor函数中抛出一个错误,那么该promise 状态为rejected。executor函数的返回值被忽略。
promise.then((value)=>{console.log(value)} //value是resolve的参数
promise.catch((value)=>{console.log(value)}) //捕获失败的错误,value是reject的参数

你可能感兴趣的:(promise)