美文网首页
Promise-03 多个then调用

Promise-03 多个then调用

作者: 呆桃冲鸭冲鸭 | 来源:发表于2020-09-11 06:55 被阅读0次
<!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个参数  1.异步 2.同步
    // 先执行了函数 后保存的函数
    // myP.then(res=>{
    //     console.log(res);
    // },err=>{
    //     console.log(err);
    // });

    // 多个then调用
    myP.then(res=>{
        console.log("1:",res);
    },err=>{
        console.log(err);
    });
    myP.then(res=>{
        console.log("2:",res);
    },err=>{
        console.log(err);
    });

</script>
</html>
promise.js:
export default class MyPromise{
    constructor(handle){
        this.state = "pending";
        this.result = undefined;
        this.resolveFnArr = [];
        this.rejectFnArr = [];
        handle(this._resolve.bind(this),this._reject.bind(this));
    };
    _resolve(val){
        this.state = "fulfilled";
        this.result = val;
         // 执行then的回调
        setTimeout(()=>{
            let cb;
            while(cb = this.resolveFnArr.shift()){
                cb && cb(val);
            };
        },0);
    };
    _reject(val){
        this.state = "rejected";
        this.result = val;
        // 执行then的回调
        setTimeout(()=>{
            let cb;
            while(cb = this.rejectFnArr.shift()){
                cb && cb(val);
            };
        },0);
    };
    then(onResolved,onRejected){
        // 异步onResolved,onRejected不会立即执行;是在调取_resolve、_reject再执行
        // 保存onResolved、onRejected
        this.resolveFnArr.push(onResolved)
        this.rejectFnArr.push(onRejected)
    };
}
打印结果

相关文章

网友评论

      本文标题:Promise-03 多个then调用

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