Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

第四十题:实现一个Promise #40

Open
Ray-56 opened this issue Oct 11, 2019 · 1 comment
Open

第四十题:实现一个Promise #40

Ray-56 opened this issue Oct 11, 2019 · 1 comment
Labels
JavaScript 解释型编程语言

Comments

@Ray-56
Copy link
Owner

Ray-56 commented Oct 11, 2019

实现一个 Promise

@Ray-56 Ray-56 added the JavaScript 解释型编程语言 label Oct 11, 2019
@MMmaXingXing
Copy link

Promise

Promise采用面向对象的方式封装了回调函数,可以将回调金字塔改为链式调用。Promise是一种规范,ES6选择了Promise A+的方案

代码实现

// 简易版
class Promise {
    constructor(init) {
        this.PromiseStste = 'pending';
        let resolve = (val) => {
            if (this.resolveCallBack) {
                this.PromiseStste = 'fulfilled';
                this.resolveCallBack(val);
            }
        }

        let reject = (val) => {
            if (this.resolveCallBack) {
                this.PromiseStste = 'reject';
                this.rejectCallBack(val);
            }
        }

        if (init) {
            init(resolve, reject);
        }
    }
    then(onFulfill, onReject) {
        this.resolveCallBack = onFulfill;
        this.rejectCallBack = onReject;
        return this
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
JavaScript 解释型编程语言
Projects
None yet
Development

No branches or pull requests

2 participants