• 封装原生promise函数


    阿里面试题:

    手动封装promise函数

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
    <script>
        /*
        *Promise实现思路
        * 1.构造函数
        * 2.回调函数的参数 resolve reject
        * 3.链式调用.then .catch
        */
    
        function PromiseM(cb){
            //初始状态
            this.status = "pending";
            this.msg = "";
    
            cb((data)=>{
                this.status = "resolve";
                this.msg = data;
            },()=>{
                this.status = "reject";
            })
            return this;
        }
    
        //链式调用.then
        PromiseM.prototype.then = function(){
            var cb = arguments;
    
            //轮询实现异步
            timer = setInterval(()=>{
                if(this.status == "resolve"){
                    //成功状态的回调
                    cb[0](this.msg);
                    clearInterval(timer);
                }else if(this.status == "reject"){
                    //失败状态的回调
                    cb[1](this.msg);
                    clearInterval(timer);
                }
            },3000)
        }
    
        new PromiseM(function (resolve,reject){
            setTimeout(function (){
                console.log(1111);
                resolve('11111');/*reject也就是失败时对应的函数,由于这个例子比较简单*/
            },1000)
        }).then(function (data){
            console.log("接收的值为"+data);
        })
    
    </script>
    </body>
    </html>
  • 相关阅读:
    2018年7月10日笔记
    2018年7月7日笔记
    2018年7月5日笔记
    2018年7月3日笔记
    sed 命令详解
    《软件构架实践》阅读笔记01
    《掌握需求过程》阅读笔记06
    《掌握需求过程》阅读笔记05
    第十二周进度条
    《掌握需求过程》阅读笔记04
  • 原文地址:https://www.cnblogs.com/-roc/p/9985127.html
Copyright © 2020-2023  润新知