Visitar URL original
第 36 期(W3C 标准-JavaScript-异步):实现一个Promise方法 · Issue #39 · fezaoduke/fe-practice-hard · GitHub
Skip to content

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

Description

@wingmeng

题目:

请实现一个合乎规范的 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
 * 来源:掘金
 * 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
 */

Activity

  1. changed the title [-]第 36 期(W3C 标准-ECMAScript-语法):实现一个Promise方法[/-] [+]第 36 期(W3C 标准-JavaScript-异步):实现一个Promise方法[/+] on Jul 21, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions