js手写系列-promise

53次阅读

共计 920 个字符,预计需要花费 3 分钟才能阅读完成。

Promise/A+ 规范

  1. 三种状态 pending || fullfiled(resolved) || rejected
  2. 当处于 pending 状态的时候,可以转移到 fullfiled(resolved) 或者 rejected 状态
  3. 当处于 fullfiled(resolved) 状态或者 rejected 状态的时候,就不可变
  • 必须有一个 then 异步执行方法,then 接收 2 个参数并且必须返回一个 promise:
  1. onFullfiled 用来接收 promise 成功的值
  2. onRejected 用语接收 promise 失败的原因
  3. promise.prototype.then = function(onFullfiled,onRejected){}

面试够用版

       function myPromise(constructor) {
            let self = this;
            self.status = 'pending';
            self.value = undefined;
            self.reason = undefined;

            function resolve(value) {if (self.status === 'pending') {
                    self.value = value;
                    self.status = 'resolved'
                }
            }

            function reject(reason) {if (self.status === 'pending') {
                    self.reason = reason;
                    self.status = 'rejected'
                }
            }
            try {constructor(resolve, reject)
            } catch (e) {reject(e)
            }
        }

        myPromise.prototype.then = function(onFullfiled, onRejected) {
            let self = this;
            switch (self.status) {
                case 'resolved':
                    onFullfiled(self.value)
                    break;
                case 'rejected':
                    onRejected(self.reason)
                    break;
                default:
            }
        }

        var p = new myPromise((resolve, reject) => {resolve(1)
        })
        p.then((x) => {console.log(x)
        })

正文完
 0