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

第 36 期(W3C 标准-JavaScript-异步):实现一个Promise方法 #39

Open
wingmeng opened this issue Jun 18, 2019 · 0 comments
Open

Comments

@wingmeng
Copy link
Collaborator

wingmeng commented Jun 18, 2019

题目:

请实现一个合乎规范的 Promise 方法。

参考答案:

class Promise {
  constructor (fn) {
    // 三个状态
    this.state = 'pending'
    this.value = undefined
    this.reason = undefined
    let resolve = value => {
      if (this.state === 'pending') {
        this.state = 'fulfilled'
        this.value = value
      }
    }
    let reject = value => {
      if (this.state === 'pending') {
        this.state = 'rejected'
        this.reason = value
      }
    }
    // 自动执行函数
    try {
      fn(resolve, reject)
    } catch (e) {
      reject(e)
    }
  }
  // then
  then(onFulfilled, onRejected) {
    switch (this.state) {
      case 'fulfilled':
        onFulfilled()
        break
      case 'rejected':
        onRejected()
        break
      default:
    }
  }
}

/**
 * 作者:陈煜仑
 * 链接:https://juejin.im/post/5d2ee123e51d4577614761f8
 * 来源:掘金
 * 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
 */
@wingmeng wingmeng changed the title 第 36 期(W3C 标准-ECMAScript-语法):实现一个Promise方法 第 36 期(W3C 标准-JavaScript-异步):实现一个Promise方法 Jul 21, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant