zoukankan      html  css  js  c++  java
  • 手写代码 -- Promise

    这里只实现了一个简单的Promise,更加完善的Promise实现请参照 Promises/A+ 标准

        class _Promise {
                constructor(fn) {
                    this.state = "pendding";
                    this.value = undefined;
                    this.resolvedCallback = [];
                    this.rejectedCallback = [];
                    fn(this.resolve.bind(this), this.reject.bind(this))
                }
    
                resolve(value) {
                    if (this.state == "pendding") {
                        this.state = "resolved";
                        this.value = value;
                        this.resolvedCallback.forEach(fn => fn(this.value))
                    }
                }
    
                reject(value) {
                    if (this.state == "pendding") {
                        this.state = "rejected";
                        this.value = value;
                        this.rejectedCallback.forEach(fn => fn(this.value))
                    }
                }
    
                then(resolve = () => {}, reject = () => {}) {
                    if (this.state == "pendding") {
                        this.resolvedCallback.push(resolve)
                        this.rejectedCallback.push(reject)
                    }
                    if (this.state == "resolved") {
                        resolve(this.value)
                    }
                    if (this.state == "rejected") {
                        reject(this.value)
                    }
                }
            }

    简单的测试一下

            new _Promise((resolve, reject) => {
                setTimeout(()=>{
                    resolve("hello")
                }, 2000)
            }).then(res => {
                console.log(res)
            }, err => {
                console.log("err", err)
            })    
  • 相关阅读:
    My Houdini First Step
    MaxScript随机赋材质
    Groups of Operators
    Select groups in scene
    投篮球
    U3D PlayMovie
    unicornForest
    MaxScript Spinner/progressBar
    MaxScript Button
    MaxScript 扇子打开
  • 原文地址:https://www.cnblogs.com/tcxq/p/13807456.html
Copyright © 2011-2022 走看看