手写Promise

Daming 2019-07-25
0条评论 293 次浏览
Daming 2019-07-250条评论 293 次浏览
    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)
    })
1+

发表评论

电子邮件地址不会被公开。