手写Promise

东明兄 2019-07-25
0条评论 1,231 次浏览
东明兄 2019-07-250条评论 1,231 次浏览
    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)
    })

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注