初步了解 promise-02 简单手写源码
废话不多说·· 直接上 简单手写 promise 源码
/** *@ 简单手写 prosmise 方法 */ const enum_pending = "pending"; const enum_resolved = "resolved"; const enum_rejected = "rejected"; function Promise(executor) { let selt = this; //初始化状态 selt.value = undefined; selt.reason = undefined; selt.status = enum_pending; //定义存放then成功的回调数组 selt.onResolvedCallbacks = []; selt.onRejectedCallbacks = []; //成功执行 function resolve(value) { //等待的状态(pending)才可以执行 并设置成功的状态 if (selt.status === enum_pending) { selt.value = value; selt.status = enum_resolved; selt.onResolvedCallbacks.forEach(fn => fn()); } } //失败执行 function reject(reason) { //等待的状态(pending)才可以执行 并设置失败的状态 if (selt.status===enum_pending){ selt.reason= reason; selt.status=enum_rejected; selt.onRejectedCallbacks.forEach(fn=>fn()); } } //异常就走失败 try { executor(resolve,reject); }catch (e) { reject(e); } }; //定义 promise then 方法 Promise.prototype.then = function (onFulfilled, onRejected) { let self = this; //根据状态执行对应的方法 if (self.status === enum_resolved) { onFulfilled(self.value); } if (self.status === enum_rejected) { onRejected(self.value); } if (self.status === enum_pending) { //保存回调函数 self.onResolvedCallbacks.push(() => { onFulfilled(self.value); }); self.onRejectedCallbacks.push(() => { onRejected(self.value); }) } } module.exports = Promise;
调用:
let Promise = require("./01.promise"); let promise = new Promise((resolve,reject)=>{ resolve() }) promise.then((data)=>{ console.log("成功·"); },(err)=>{ console.log("失败·"); });