40行js完成一个浅易Promise

近来口试有问到Promise的道理,以及完成的要领。所以本身着手完成了一个,发个文章记录下。
简朴剖析下,promise实例对象有两个属性,一个是status,一个是value。另有一个then要领。
status有3个状况,pending,resolved,rejected。value就是then回调的时刻传的值。
下面是代码

/* 
  原生js模仿promise
*/
const PromisePolyfill = (() => {
    //状况治理
    const promiseStatusSymbol = Symbol('PromiseStatus');
    const promiseValueSymbol = Symbol('PromiseValue');
    const STATUS = {
        PENDING: 'PENDING',
        FULFILLED: 'FULFILLED',
        REJECTED: 'REJECTED'
    };
    //resolve操纵设置值和状况
    function resolve() {
        this[promiseValueSymbol] = arguments[0];
        this[promiseStatusSymbol] = STATUS['FULFILLED'];
    }
    //reject操纵设置值和状况
    function reject() {
        this[promiseValueSymbol] = arguments[0];
        this[promiseStatusSymbol] = STATUS['REJECTED'];
    }

    class myPromise {
        constructor(resolver) {
            if (typeof resolver !== 'function') {
                throw new TypeError(`parameter 1 must be a function, but get a ${typeof func}`);
            }
            this[promiseStatusSymbol] = STATUS['PENDING'];//初始状况为pending
            resolver(
                resolve.bind(this),//绑定promise实例对象
                reject.bind(this)
            );
        }
        then(callback) {
            //开一个定时器监听状况变化,如果有变化则实行callback
            const interval = setInterval(() => {
                if (this[promiseStatusSymbol] === 'FULFILLED' || this[promiseStatusSymbol] === 'REJECTED') {
                    clearInterval(interval);
                    callback(this[promiseValueSymbol], resolve.bind(this), reject.bind(this));
                    this[promiseStatusSymbol] = 'PENDING';//实行完后把状况改回,轻易下一个then要领举行定时轮询
                }
            });
            return this;
        }
    }
    return myPromise;
})();

写完了丢到控制台测试,圆满预期运转

//测试,下面会先打印出111,再打印出222,333
new PromisePolyfill(function (resolve, reject) {
    setTimeout(() => {
        resolve(222);
        console.log(111)
    }, 1000);
}).then(function (res, resolve, reject) {
    setTimeout(() => {
        resolve(333);
        console.log(res)
    }, 3000);
}).then(function (res, resolve, reject) {
    console.log(res);
});

代码github地点:https://github.com/leeseean/P…

    原文作者:all2005
    原文地址: https://segmentfault.com/a/1190000013615320
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞