手写Promies && AJAX

Promise


一、Promise 是一个异步操作返回的对象,用来传递异步操作的消息,
根据自己对 Promise 的理解,实现一个Promise :
Promise 有三种状态:Pending 初始态; Fulfilled 成功态; Rejected失败态

function Promise(executor) {
    let self = this;
    self.statuts = 'pending'; //等状态
    self.value = undefined; //成功的返回值
    self.reason = undefined; //失败的返回值

    function resolve(value) {
        if (self.statuts === 'pending') {
            self.statuts = 'resolved';
            self.value = value;
        }
    }
    function reject(reason) {
        if (self.statuts === 'pending') {
            self.statuts = 'rejected';
            self.reason = reason;
        }
    }
    try {
        executor(resolve, reject)
    } catch (e) {
        reject(e); //捕获时如果发生异常,就直接失败
    }
}

//onFufiled 成功的回调
//onRejected 失败的回调
Promise.prototype.then = function (onFufiled, onRejected) {
    let self = this;
    if (self.status === 'resolved') {
        onFufiled(self.value);
    }
    if (self.status === 'rejected') {
        onRejected(self.reason);
    }
}
module.exports = Promise;

来测试一下子:

let Promise = require('./Promise');
    let Promise = new Promise(function (resolve, reject) {
        resolve(100);
    });

    Promise.then(function (data) {
        console.log('data:', data);
    }, function (err) {
        console.log('err', err);
    });

    //输出:data: 100
}

Promise 实例可以多次then,当成功后会将 then 中的成功方法按顺序执行,我们可以先将 then 中成功的回调和失败的回调存到数组内。当成功的时候调用成功的数组即可

self.onResolvedCallbacks = [];  /* 存放then成功的回调*/
self.onRejectedCallbacks = [];  /* 存放then失败的回调*/
function resolve(value){
    if(self.status === 'pending'){
        self.status = 'resolved';
        self.value = value;
        self.onResolvedCallbacks.forEach(function (fn) {
            fn();
        })
    }
}
function reject(reason) {
    if(self.status === 'pending') {
        self.status = 'rejected';
        self.reason = reason;
        self.onRejectedCallbacks.forEach(function (fn) {
            fn();
        })
    }
}

复制代码if(self.status === 'pending'){
    self.onResolvedCallbacks.push(function () {
        onFufiled(self.value);
    })
    self.onRejectedCallbacks.push(function () {
        onRejected(self.reason);
    })
}

手写 AJAX

//背代码,完整版
    var request = new XMLHttpRequest()
    request.open('GET', 'a/b/c?name=ff', true);
    request.onreadystatechange = function () {
        if (request.readyState === 4 && request.status === 200) {
            console.log(request.responseText);
        }
    }
    request.send()

    // 背代码,简化版
    var request = new XMLHttpRequest()
    request.open('GET', 'a/b/c?name=ff', true)
    request.onload = () => console.log(request.responseText)
    request.send()

你可能感兴趣的:(手写Promies && AJAX)