手写Promise

chat
    function Promise1(executor) {
        var _this = this;
        this.status = "pending";//状态
        this.value = undefined;//成功 结果
        this.reason = undefined;//用来 保存失败原因
        this.onFulfilledFunc = [];//用来暂存成功回调
        this.onRejectedFunc = [];//用来暂存 失败回调
        executor(resolve, reject);

        function resolve(value) {
            if (_this.status === "pending") {
                _this.value = value;
                _this.onFulfilledFunc.forEach(function (fn) {
                    fn(value)
                });
                _this.status = "resolved";

            }

        }

        function reject(reason) {
            if (_this.status === "pending") {
                _this.reason = reason;
                _this.onRejectedFunc.forEach(function (fn) {
                    fn(reason);
                })
                _this.status = "rejected"
            }

        }

    }

    Promise1.prototype.then = function (onFulfilled, onRejected) {

        if (this.status === "resolved") {
            if (typeof onFulfilled === "function") {
                onFulfilled(this.value)
            }
        } else if (this.status === "rejected") {
            if (typeof onRejected === "function") {
                onRejected(this.reason)
            }
        } else if (this.status === 'pending') {

            if (typeof onFulfilled === "function") {
                this.onFulfilledFunc.push(onFulfilled)
            }

            if (typeof onRejected === "function") {
                this.onRejectedFunc.push(onRejected);
            }

        }

    }

 var a = new Promise1(function (resolve, reject) {
        setTimeout(function () {
            console.log(123);
            resolve("are you ok")
        }, 10000)
    })

版权声明:
作者:东明兄
链接:https://blog.crazyming.com/note/1735/
来源:CrazyMing
文章版权归作者所有,未经允许请勿转载。

THE END
分享
二维码
海报
手写Promise
function Promise1(executor) { var _this = this; this.status = "pending";//状态 this.value = undefined;//成功 结果 ……
<<上一篇
下一篇>>
chat