<!DOCTYPE html> <html lang="en"> <head> <Meta charset="UTF-8" /> <Meta http-equiv="X-UA-Compatible" content="IE=edge" /> <Meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>promise A+ 规范</title> </head> <body> <script> let a = `onFulfilled,onRejected 不会立马调用,而是被留存下来,留存到整个promise 进入已决状态,根据状态的区分而进行调用,所以这里不能用一个变量 而是用一个数组 then是可以绑定多次的, `; const PENDING = 'pending'; const FULFILLED = 'fulfilled'; const REJECTED = 'rejected'; class myPromise { constructor(executor) { this.status = PENDING; this.data = null; this.reason = null; this.dispatchers = []; try { executor(this.__resolve.bind(this), this.__reject.bind(this)); } catch (err) { this.__reject(err); } } __resolve(data) { this.__updateStatus(FULFILLED); this.data = data; this.__executedispatchers(); } __reject(reason) { this.__updateStatus(REJECTED); this.reason = reason; this.__executedispatchers(); } then(onFulfilled, onRejected) { return new myPromise((resolve, reject) => { this.dispatchers.push( { status: FULFILLED, dispatcher: onFulfilled, resolve, reject }, { status: REJECTED, dispatcher: onRejected, resolve, reject } ); }); } catch(onRejected) { this.then(null, onRejected); } __updateStatus(newStatus) { if (this.status !== PENDING) return; this.status = newStatus; } __executedispatchers() { if (this.status === PENDING) return; for (const dispatcherConf of this.dispatchers) { this.__executedispatcher(dispatcherConf); } } __executedispatcher({ status, dispatcher, resolve, reject }) { if (this.status !== status) return; if (typeof dispatcher !== 'function') { this.status === FULFILLED ? resolve(this.data) : reject(this.data); } try { const result = dispatcher(this.status === FULFILLED ? this.data : this.reason); resolve(result); } catch (err) { reject(err); } } } const myPro = new myPromise((resolve, reject) => { setTimeout(() => { resolve(11); }, 1000); }); myPro.then(r => { console.log(r); }); </script> </body> </html>
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。