Promise 库
;(function (global) { // 严格模式 "use strict"; // 定义状态 promise 的三种状态 const PENDING = 'pending'; const RESOLVED = 'resolved'; const REJECTED = 'rejected'; /** * Promise 构造器函数 * @param {function} executor 执行器 */ function Promise(executor) { // 保存原始 this 指向 const self = this; // 默认 pending 状态 this.status = PENDING; // 用来保存状态结果的 this.data = null; // 如果执行异步任务,then 是不会立刻执行的,需要保存下来,以便状态改变后调用回调 this.callbacks = []; /** * 状态变为成功的函数 * @param {*} value * @returns */ function resolve(value) { // 做一层防护,一旦发生变化就不能够改变 return 终止。 if (self.status !== PENDING) { return; } // 改变状态,存储数据 self.status = RESOLVED; self.data = value; // 判断是否已经存了回调,有的话执行回调 if (self.callbacks.length > 0) { setTimeout(() => { self.callbacks.forEach(callback => { callback.onResolved(self.data); }) }); } } /** * 状态变为失败的函数 * @param {*} reason * @returns */ function reject(reason) { // 做一层防护,一旦发生变化就不能够改变 return 终止。 if (self.status !== PENDING) { return; } // 改变状态,存储数据 self.status = REJECTED; self.data = reason; // 判断是否已经存了回调,有的话执行回调 if (self.callbacks.length > 0) { setTimeout(() => { self.callbacks.forEach(callback => { callback.onRejected(self.data); }) }); } } // 执行执行器 executor,并且捕获 throw 抛出的错误 try { executor(resolve, reject); } catch (error) { reject(error); } } /** * 构造函数原型的then方法。 * @param {function} onResolved * @param {function} onRejected */ Promise.prototype.then = function (onResolved, onRejected) { // 向后传递成功的value onResolved = typeof onResolved === 'function' ? onResolved : value => value; // 实现异常穿透 catch 捕获 onRejected = typeof onRejected === 'function' ? onRejected : reason => {throw reason}; // 保存原始 this 指向 const self = this; // 需要返回一个 promise return new Promise((resolve, reject) => { // 封装统一的结构 function handle(callback) { try { // 回调返回的结构 result const result = callback(self.data); if (result instanceof Promise) { // 如果返回的还是一个 promise // 此时 then 返回的 promise 是由新的返回的 promise 的状态来决定的。 // result.then(resolve, reject); // console.log(result); result.then( value => resolve(value), reason => reject(reason) ); } else { // 如果返回的还是一个非 promise,总是以成功的状态传递结果 result resolve(result); } } catch (error) { // 是以 throw 抛出传递的错误 reject(error); } } // 如果状态是 pending 中,需要存下回调 {onResolved: Function, onRejected: Function} if (this.status === PENDING) { this.callbacks.push({ onResolved() { handle(onResolved); }, onRejected() { handle(onResolved); } }) // 状态已经变成成功 } else if (this.status === RESOLVED) { setTimeout(() => { handle(onResolved); }); // 状态已经变为失败 } else { setTimeout(() => { handle(onRejected); }); } }) } Promise.resolve = function (value) { return new Promise((resolve, reject) => { // value 是 promise // console.log(value); if (value instanceof Promise) { // 使用value的结果作为promise的结果 value.then( value => resolve(value), reason => reject(reason) ) // value.then(resolve, reject); } else { resolve(value); } // value 不是 promise }) } /** * * @param {*} reason * @returns */ Promise.reject = function (reason) { // 返回一个失败的 promise // console.log(1); return new Promise((resolve, reject) => { reject(reason); }) } Promise.all = function (promises) { // 保存所有成功value数组 // const values = []; const values = new Array(promises.length); // 用来保存成功 promise 的数量 let resolvedCount = 0; return new Promise((resolve, reject) => { // promises 来决定 // 遍历获取每个 promise 的结果 promises.forEach((item, index) => { item.then( value => { // 成功,将值保存在values中 resolvedCount = resolvedCount + 1; values[index] = values; // 如果全部成功,改为成功 if (resolvedCount === promises.length) { resolve(values); } }, reason => { // 只要有一个失败了,都为失败 reject(reason); } ) }) }) } Promise.race = function (promises) { return new Promise((resolve, reject) => { for (var i = 0; i < promises.length; i++) { promises.then( value => resolve(value), reason => reject(reason) ) } }) } /** * 构造函数原型的catch方法。 * @param {*} onRejected * @returns */ Promise.prototype.catch = function (onRejected) { // 返回一个 promise return this.then(undefined, onRejected); } if (typeof module !== 'undefined' && module.exports) { // 兼容 CommonJs 规范 module.exports = Promise; } else if (typeof define === 'function') { // 兼容 AMD/CMD 规范 define(function () { return Promise; }) } else { // 注册全局变量 global.Promise = Promise; } })(this);
Class 版
class Promose { constructor() { const PENDING = 'pending'; const RESOLVED = 'resolved'; const REJECTED = 'rejected'; // 保存原始 this 指向 const self = this; // 默认 pending 状态 this.status = PENDING; // 用来保存状态结果的 this.data = null; // 如果执行异步任务,then 是不会立刻执行的,需要保存下来,以便状态改变后调用回调 this.callbacks = []; /** * 状态变为成功的函数 * @param {*} value * @returns */ function resolve(value) { // 做一层防护,一旦发生变化就不能够改变 return 终止。 if (self.status !== PENDING) { return; } // 改变状态,存储数据 self.status = RESOLVED; self.data = value; // 判断是否已经存了回调,有的话执行回调 if (self.callbacks.length > 0) { setTimeout(() => { self.callbacks.forEach(callback => { callback.onResolved(self.data); }) }); } } /** * 状态变为失败的函数 * @param {*} reason * @returns */ function reject(reason) { // 做一层防护,一旦发生变化就不能够改变 return 终止。 if (self.status !== PENDING) { return; } // 改变状态,存储数据 self.status = REJECTED; self.data = reason; // 判断是否已经存了回调,有的话执行回调 if (self.callbacks.length > 0) { setTimeout(() => { self.callbacks.forEach(callback => { callback.onRejected(self.data); }) }); } } // 执行执行器 executor,并且捕获 throw 抛出的错误 try { executor(resolve, reject); } catch (error) { reject(error); } } then(onResolved, onRejected) { // 向后传递成功的value onResolved = typeof onResolved === 'function' ? onResolved : value => value; // 实现异常穿透 catch 捕获 onRejected = typeof onRejected === 'function' ? onRejected : reason => {throw reason}; // 保存原始 this 指向 const self = this; // 需要返回一个 promise return new Promise((resolve, reject) => { // 封装统一的结构 function handle(callback) { try { // 回调返回的结构 result const result = callback(self.data); if (result instanceof Promise) { // 如果返回的还是一个 promise // 此时 then 返回的 promise 是由新的返回的 promise 的状态来决定的。 // result.then(resolve, reject); // console.log(result); result.then( value => resolve(value), reason => reject(reason) ); } else { // 如果返回的还是一个非 promise,总是以成功的状态传递结果 result resolve(result); } } catch (error) { // 是以 throw 抛出传递的错误 reject(error); } } // 如果状态是 pending 中,需要存下回调 {onResolved: Function, onRejected: Function} if (this.status === PENDING) { this.callbacks.push({ onResolved() { handle(onResolved); }, onRejected() { handle(onResolved); } }) // 状态已经变成成功 } else if (this.status === RESOLVED) { setTimeout(() => { handle(onResolved); }); // 状态已经变为失败 } else { setTimeout(() => { handle(onRejected); }); } }) } // catch catch(onRejected) { // 返回一个 promise return this.then(undefined, onRejected); } // resolve 方法 static resolve(value) { return new Promise((resolve, reject) => { // value 是 promise // console.log(value); if (value instanceof Promise) { // 使用value的结果作为promise的结果 value.then( value => resolve(value), reason => reject(reason) ) // value.then(resolve, reject); } else { resolve(value); } // value 不是 promise }) } // reject 方法 static reject(reason) { // 返回一个失败的 promise // console.log(1); return new Promise((resolve, reject) => { reject(reason); }) } // all 方法 static all(promises) { // 保存所有成功value数组 // const values = []; const values = new Array(promises.length); // 用来保存成功 promise 的数量 let resolvedCount = 0; return new Promise((resolve, reject) => { // promises 来决定 // 遍历获取每个 promise 的结果 promises.forEach((item, index) => { item.then( value => { // 成功,将值保存在values中 resolvedCount = resolvedCount + 1; values[index] = values; // 如果全部成功,改为成功 if (resolvedCount === promises.length) { resolve(values); } }, reason => { // 只要有一个失败了,都为失败 reject(reason); } ) }) }) } // race 方法 static race(promises) { return new Promise((resolve, reject) => { for (var i = 0; i < promises.length; i++) { promises.then( value => resolve(value), reason => reject(reason) ) } }) } }