zhuanghaixin / Interview

8 stars 0 forks source link

Promise扩展-Promise进度通知 #221

Open zhuanghaixin opened 2 years ago

zhuanghaixin commented 2 years ago
<!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>Document</title>
</head>
<body>
    <script>
    class TrackablePromise extends Promise{
        constructor(executor){
            const notifyHandlers=[]; // 定义一个通知处理数组
            super((resolve,reject)=>{
                return executor(resolve,reject,(status)=>{
                    notifyHandlers.map(handler=>handler(status))
                })
            })
            this.notifyHandlers=notifyHandlers
        }
        notify(notifyHandler){
            this.notifyHandlers.push(notifyHandler)
            return this
        }
    }
    let p = new TrackablePromise((resolve, reject,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((value)=>setTimeout(console.log,0,`completed${value}`))

    // notify()函数会返回期约,所以可以连续调用,连续添加处理程序。多个处理程序会针对收到的每条消息分别执行一遍。

    // p.notify((x)=>setTimeout(console.log,0,'a',x)).notify((x)=>setTimeout(console.log,0,'b:',x))

    // p.then(()=>setTimeout(console.log,0,'completed'))

    </script>

</body>
</html>

image