在看《Javascript 高级程序设计》这本书的时候,在读到《期约与异步函数》这一章节中的一个例子的时候,其示例代码看了好几遍才看的更加明白,这其中有很大程度上是我菜的缘故,但是……,所以在这里做下记录。
这段代码旨在构造一个具备进度追踪的promise拓展类:
class TrackablePromise extends Promise{ constructor(executor){ const notifyHandlers=[] super((resolve,rejcet)=>{ return executor(resolve,rejcet,(status)=>{ notifyHandlers.map(handler=>handler(status)) }) }) this.notifyHandlers=notifyHandlers } notify(notifyHandler){ this.notifyHandlers.push(notifyHandler) return this }}
示例代码如下:
let p = new TrackablePromise((resolve,rejcet,notify)=>{ function countdown(x) { if(x>0){ notify(`${20*x}% remaining`) setTimeout(()=>countdown(x-1),1000) }else{ resolve() } } countdown(5)})p.notify((x)=>setTimeout(console.log,0,'progress:',x))p.then(()=>setTimeout(console.log,0,'completed'))//书上写的打印结果如下:
(约1秒后) 80% remaining
(约2秒后) 60% remaining
(约3秒后) 40% remaining
(约4秒后) 20% remaining
(约5秒后) completed
//实际的打印结果应该是:
progress: 80% remaining
progress: 60% remaining
progress: 40% remaining
progress: 20% remaining
completed
这个代码看的比较头疼额点在于:
- 在实例化TrackablePromise类的时候,所选用的参数名称 notify和TrackablePromise类的方法notify 叫一个名字,让人在读代码的时候产生混淆
- 书上印的打印结果和实际打印结果不同
- 构造函数代码(status)=>{notifyHandlers.map(handler=>handler(status)}因为函数执行需要,嵌套得双重箭头函数也看起来很不友好。但是这里必须要这么写,因为notifyHandlers只有写成数组,才好向其中传入函数作为参数。