promise A+ 第二遍
2022/5/5 23:43:33
本文主要是介绍promise A+ 第二遍,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
<!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>
这篇关于promise A+ 第二遍的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-05-20测试人员都是画画大神,让我看看谁还不会用代码图?
- 2024-05-20年薪百万的程序员都在用的摸鱼方式……
- 2024-05-19永别了,微服务架构!
- 2024-05-15鸿蒙生态设备数量超8亿台
- 2024-05-13TiDB + ES:转转业财系统亿级数据存储优化实践
- 2024-05-09“2024鸿蒙零基础快速实战-仿抖音App开发(ArkTS版)”实战课程已上线
- 2024-05-09聊聊如何通过arthas-tunnel-server来远程管理所有需要arthas监控的应用
- 2024-05-09log4j2这么配就对了
- 2024-05-09nginx修改Content-Type
- 2024-05-09Redis多数据源,看这篇就够了