关于promise.then执行顺序,如何理解?

Promise.resolve().then(() => { console.log(0); return Promise.resolve(4)…
关注者
11
被浏览
534

3 个回答

请跳转到另一个问题

关于promise输出顺序的疑问?

继续浏览内容
知乎
发现更大的世界
打开
浏览器
继续

promise只是一种设计实现,也就是使用基础语法自己也可以实现 Promise,下面哥哥给你实现一个基本版的promis:

class Promise2 {

    constructor(main: (resolve: Function, reject?: Function) => any) {
        this.main = main;
    }

    main;
    resolves = Array<Function>();
    rejects = Array<Function>();
    __isRunning = false;

    then(callback: Function) {
        this.resolves.push(callback);
        this.__run();
        return this;
    }

    catch(callback: Function) {
        this.rejects.push(callback);
        this.__run();
        return this;
    }

    __run() {
        if (this.__isRunning) return;
        this.__isRunning = true;
        setTimeout(this.main.bind(this, this.__resolve.bind(this), this.__reject.bind(this)));
    }

    __resolve(resp) {
        try {
            while (this.resolves.length) {
                resp = this.resolves.shift().call(this, resp);
            }
        } catch (e) {
            this.__reject(e);
        }
    }

    __reject(e) {
        while (this.rejects.length) {
            e = this.rejects.shift().call(this, e);
        }
    }
}

// 测试
let p = new Promise2((resolve, reject) => {
    setTimeout(() => {
        if (Math.random() > .5) {
            resolve("success")
        } else {
            reject("error");
        }
    }, 1000);
}).then(resp => {
    console.log(resp);
}).catch(e => {
    console.log(e);
});

继续浏览内容
知乎
发现更大的世界
打开
浏览器
继续