美文网首页
Promise-02 then参数

Promise-02 then参数

作者: 呆桃冲鸭冲鸭 | 来源:发表于2020-09-10 21:00 被阅读0次

    then 2个参数 : 1.异步 2.同步

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>my</title>
    </head>
    <body>
        <p>test my</p>
    </body>
    <script type="module">
        //  type="module" 严格模式 
        import MyPromise from './promise.js';
        // 三种状态 1.pending 2.fulfilled 3.rejected
        let myP = new MyPromise((resolve,reject)=>{
            setTimeout(()=>{
                console.log('====')
                resolve("suc...");
            });
            // reject("err...");
        });
        // console.log(myP);
        
        //then 2个参数 
        myP.then(res=>{
            console.log(res);
        },err=>{
            console.log(err);
        })
    
    </script>
    </html>
    
    promise.js:
    export default class MyPromise{
        constructor(handle){
            this.state = "pending";
            this.result = undefined;
            this.resolveFn = undefined;
            this.rejectFn = undefined;
            handle(this._resolve.bind(this),this._reject.bind(this));
        };
        _resolve(val){
            this.state = "fulfilled";
            this.result = val;
            setTimeout(()=>{
                this.resolveFn(val);
            },0);
            // 执行then的回调
            // this.resolveFn(val);
        };
        _reject(val){
            this.state = "rejected";
            this.result = val;
            setTimeout(()=>{
                this.rejectFn(val);
            },0);
            // 执行then的回调
            // this.rejectFn(val);
        };
        then(onResolved,onRejected){
            // console.log(onResolved,onRejected,'-----');
            //判断里面执行then里的参数,只能处理同步问题
            // if(this.state === "fulfilled"){
            //     onResolved && onResolved(this.result)
            // }else if(this.state === "rejected"){
            //     onRejected && onRejected(this.result)
            // };
    
            // 异步onResolved,onRejected不会立即执行;是在调取_resolve、_reject再执行
            // 保存onResolved、onRejected
            this.resolveFn = onResolved;
            this.rejectFn = onRejected;
        };
    }
    

    相关文章

      网友评论

          本文标题:Promise-02 then参数

          本文链接:https://www.haomeiwen.com/subject/nxspektx.html