//E6 中采用了 Promise/A+ 规范 //完整版本实现 Promise class MyPromise { // 放入callbacks队列,其实也就是注册回调函数,可以向观察者模式方向思考; callbacks = []; state = "pending" //增加状态 value = null; //保存结果 // Promise对象接受一个回调函数作为参数, //该回调函数接受两个参数,分别是成功时的回调resolve和失败时的回调reject constructor(fn) { //第一个参数 成功时的回调resolve fn(this._resolve.bind(this)) } //接受两个参数 then(onfulfilled) { // then 返回的一定是一个新的Promise实例 return new MyPromise(resolve=>{ this._handle({ onfulfilled: onfulfilled ||null, resolve:resolve }) }); //在resolve 之前,跟之前的逻辑一样,添加到callbacks中 // if (this.state === "pending") { // this.callbacks.push(onfulfilled); // } else { // //在resolve之后,直接执行回调,返回结果 // onfulfilled(this.value) // } //而不是返回当前实例的this对象 // return this; 实现链式调用操作 // 真正的链式 Promise 是指在当前 Promise 达到 fulfilled 状态后面的状态一样 } _handle(callback){ console.log(callback.onfulfilled) if(this.state==="pending"){ this.callbacks.push(callback); return; } //如果then中没有传递任何东西 if(!callback.onfulfilled){ callback.resolve(this.value) return; } let ret=callback.onfulfilled(this.value); callback.resolve(ret); } //resolve 接受一个参数支持任意类型 _resolve(value) { // 通过 setTimeout 机制,将 resolve 中执行回调的逻辑放置到JS任务队列末尾,以保证在 resolve 执行时,then方法的 onFulfilled 已经注册完成 this.state = "fulfilled" //改变成成功状态 this.value = value; //保存结果 // setTimeout(() => { //通过改变状态直接返回结果 // this.callbacks.forEach(fn => fn(value)); // }) this.callbacks.forEach(callback=>this._handle(callback)) } } let p = new MyPromise(resolve => { // setTimeout(() => { //增加延迟调用实现同步 去除settimeout去掉"同步执行“没有打印结果,我们可以在mypromise加延迟操作, resolve("5秒") // }, 5000); }) let p1 = p.then(e => { console.log("1", e); }).then(e => { console.log("2", e); }) //.then(e => { // console.log("3", e); // }) // setTimeout(() => { // p1.then(e => { // console.log("disange" + e); // }) // });
原文:https://www.cnblogs.com/James-net/p/14006770.html