简易实现+链式调用(值唯一)+状态+延迟机制
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
| class Promise { constructor(executor){ executor(this.resolve) } cb = [] state = 'pending' value = null then(onFullfilled) { if (this.state === 'pending') { this.cb.push(onFullfilled) } else { onFullfilled(this.value) } return this } resolve = (value) => { if (this.state === 'pending') { this.state === 'fullfilled' } this.value = value this.cb.forEach(fn => fn(value)) } }
let p = new Promise((resolve) => { setTimeout(() => { resolve(3) }, 1000); })
p.then((value) => { console.log(value) })
|
ref
https://mp.weixin.qq.com/s/UNzYgpnKzmW6bAapYxnXRQ
https://mp.weixin.qq.com/s?__biz=MzI4NjY4MTU5Nw==&mid=2247486706&idx=2&sn=9434eb4f5ea43e46de70a6486afbffbf&chksm=ebd87c60dcaff57669d389cf114a993b15df789b1b14fe1f4c89e38d304d79489dc5394e9296&cur_album_id=1500522652875194368&scene=189#wechat_redirect