zoukankan      html  css  js  c++  java
  • 封装原生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>
  • 相关阅读:
    机器人能都返回原点
    解码字母
    学习W3C
    字符重排
    字符串相加
    ARC107F Sum of Abs
    6830. 【2020.10.25提高组模拟】排列
    6828. 【2020.10.25提高组模拟】幂
    CF1434D Roads and Ramen
    2020 计蒜之道 线上决赛 C 攀登山峰
  • 原文地址:https://www.cnblogs.com/-roc/p/9985127.html
Copyright © 2011-2022 走看看