promise 原理

<!DOCTYPE html><br /><html lang="en"><br /><head><br />    <meta charset="UTF-8"><br />    <title>Title</title><br /></head><br /><body><br />TEST PROMISE<br /><div><br />    <h1>promise 原理</h1><br />    <p><br />        Promise 是一个构造函数:<br />    <ul><br />        <li>Promise:接受一个执行函数</li><br />        <li>执行函数里面两个形参:resolve,reject</li><br />        <li><br />            <p>Promise的原型上面有个then方法,这个方法接受两个参数(resolveCallback,rejectCallback)</p><br />            <p>并且把这个两个方法保存到promise的一个回调数组里面,当执行resolve的时候,根据status执行对应的回调方法</p><br />            <p>如果需要链式回调,则在then方法里面,返回一个新的promise对象,在回调数组里面保存resolveCallback,rejectCallback,和新的promise对象的resolve,reject方法</p><br />            <p>然后在resolve方法里面执行回调数组里面的resolve方法</p><br />        </li><br />    </ul><br />    </p><br /></div><br /></body><br /><script><br />    function MyPromise(fn) {<br />        var _this = this<br />        _this.value = null; // resolve,reject的值<br />        _this.status = 'Pending' // promise 的状态,Pending:初始,Fulfilled:resolve,Rejected:reject<br /><br />        _this.deffers = [] // 回调数组每调用一次then,就万里面push一个{onFullFilled:onFullFilled,onRejected:onRejected}<br />        function resolve(val) {<br />            if (_this.status === 'Pending') {<br />                _this.status = 'Fulfilled'<br />                _this.value = val<br />                _this.deffers.forEach(function (item) {<br />                    var res;<br />                    var onFullFilled = item.cb<br />                    var resolve = item.resolve<br />                    onFullFilled && (res = onFullFilled(_this.value))<br />                    if (typeof res === 'object' && res.then) {<br />                        res.then(resolve)<br />                    }else {<br />                        resolve && resolve(res)<br />                    }<br />                })<br />            }<br />        }<br />        function reject(val) {<br />        }<br />        fn(resolve,reject)<br /><br />    }<br />    MyPromise.prototype.then = function (onFullFilled,onRejected) {<br />        var _this = this<br />        return new MyPromise(function (resolve,reject) {<br />            _this.deffers.push({<br />                cb:onFullFilled,<br />                resolve:resolve<br />            })<br />        })<br />    }<br /><br />    var a = new MyPromise(function (reslove,reject) {<br />        setTimeout(function () {<br />            reslove('success')<br />            reject('fail')<br />        }, 1000);<br />    })<br />    a.then(function (res) {<br />        console.log(res)<br />        return (888)<br />    }).then(function (res) {<br />        console.log(9999)<br />    })<br /></script><br /></html>