发布于 2026-01-06 7 阅读
0

构建零承诺

构建零承诺

公众的节奏是公共的,我们的承诺是所有的人的承诺,但我不建议您继续休闲,我们将继续为您提供更多的信息。

承诺将在未来的执行中发挥重要作用,例如,我们需要外部服务,或者您可以闲着。实际上,Promise 是一个利用PromisesA+描述的特定对象实现的项目

与承诺和承诺相比,承诺的具体内容和实施承诺做到零!

规格

没有 JavaScript 的 Promises 的具体说明是 Promises/A+(Promises/A的演变),它是原生实现的前提,是 Q 和 Bluebird 实现的参考文献。解决这一问题时需要特别注意的是,要实施该模型,并以辩论者的方式提出方案。具体定义、基本方法、then功能方法、目前的 Promises 是与开发功能一致的 Promise。

术语

Vamos dar nome a algumas coisas, Primeiramente vamos definir todos os termos que vamos utilizar na nossa pronos, isto vem de uma tradução direteta da especicação:

  • Aéum Promiseobjeto com um método thencujo comportamento conforma com esta especacão
  • thenable,嗯,目标或功能,定义了方法then
  • Um valor é qualquer valor válido no JavaScript(包括undefined,um thenableou até outra promise
  • Uma exceptioné uma exceção padrão de desenvolvimento que é levantada apartir de umthrow
  • A razão é o motivo pelo qual uma promisefoi rejeitada (quando sofre uma exception)

埃斯塔多

承诺是国家的基本要素。 Ela pode estar em um de três possíveis estados:

  • 悬垂: Neste estado ela pode ir para fulfilledourejected
  • 实现(完成): Neste estado,一个承诺 não pode transicionar para nenhum outro estado; Também deve possuir um valor que não deve ser alterável
  • 拒绝 (rejeitada): Neste estado,一个承诺 não pode transicionar para nenhum outro estado; Também deve possuir uma razão que não deve ser alterável

然后

作为承诺的具体内容,我们提供了具体的方法then或响应,可以提供功能和实际价值。then下一步的开发方法:

promise.then(onFulfilled, onRejected)
Enter fullscreen mode Exit fullscreen mode

Onde,onFulfilled您可以继续以下操作:

(value: T) => void
Enter fullscreen mode Exit fullscreen mode

在此过程中,onRejected我们将勇敢地投入其中。

不过,请then注意,要考虑符合具体情况的一系列规则。 Não vou colocar todas elas aqui, mas vou incluir as mais importantes:

  • 所有onFulfilledonRejected参数都then被忽略了,但没有任何功能
  • onFulfilled, quando aceito, deve ser chamado semper após apromise ter sido resolvida, com o valor da Promise como primeiro argumento. Além disso ele só pode ser chamado uma vez。
  • onRejected, quando aceito, deve ser chamado semper após apromise ter sido rejeitada, com a razão da Promise como primeiro argumento. Além disso ele só pode ser chamado uma vez。
  • thenPode Ser encadeado múltiplas vezes na mesma 承诺。承诺已完成或已回复,待处理程序 then将按顺序执行。
  • then开发回归承诺

实施

为了实现诺萨的承诺,首先要解决问题PromiseTypes.ts,然后使用 Typescript 来实现最简单的方法。任何人都可以在全球范围内找到存在的一切,并且可以享受乐趣onFulfilledonRejected执行者和所有权利。

Vamos começar criando um enumerador com os estados possíveis de uma 承诺:

export enum PromiseStates {
  PENDING,
  FULFILLED,
  REJECTED
}
Enter fullscreen mode Exit fullscreen mode

Agora vamos criar os Tipos de apoio 和 os Tipos base da Promise que vamos usar:

export type ResolveFunction = (value: any) => any
export type RejectFunction = (reason: any) => any
export type Thennable = { then: (value: any) => TypePromise }
export type ExecutorFunction = (resolve: ResolveFunction, reject: RejectFunction) => void
Enter fullscreen mode Exit fullscreen mode

在构建器中,我们可以实现executorPromise 的功能,并与resolveeo进行交互reject。 Da mesma forma, criamos um Tipo para o thennable。 Vamos também criar um outro Tipo auxiliar so para que possamos deixar nosso mais bonito, chamado nullable<T>, ele vai servir para podermos Implementar elementos que podem ser nulos:

export type Nullable<T> = T | null
Enter fullscreen mode Exit fullscreen mode

国家机器

Vamos começar criando um arquivo chamado TypePromise.ts,vamos chamar nossa classe de TypePromisepara nãoconflitar com amplementação nativa de Promises,por enquanto ela éuma simples máquina de estados,考虑要办的事情 os estados que temos que ter:

import { PromiseStates, ResolveFunction, RejectFunction, ExecutorFunction, Nullable, Thennable } from './PromiseTypes'

export class TypePromise {
  private state: PromiseStates = PromiseStates.PENDING
  private value: any = null
  private thenHandlers: HandlerFunction[] = []
}
Enter fullscreen mode Exit fullscreen mode

Veja que temos um Tipo novo,HandlerFunctions正如我们thencatch承诺的那样。执行处理程序的情况如下。 Cada um deles é um objeto com 作为执行人的双重功能,vamos adicionar nosso arquivo PromiseTypes.tse importar no arquivoprincipal, nosso arquivo PromiseTypes.tsfica assim:

import { TypePromise } from './TypePromise'

export enum PromiseStates {
  PENDING,
  FULFILLED,
  REJECTED
}

export type ResolveFunction = (value: any) => any
export type RejectFunction = (reason: any) => any
export type ExecutorFunction = (resolve: ResolveFunction, reject: RejectFunction) => void
export type Thennable = { then: (value: any) => TypePromise }

export type Nullable<T> = T | null

export type HandlerFunction = {
  onFulfilled?: ResolveFunction;
  onRejected?: Nullable<RejectFunction>
}
Enter fullscreen mode Exit fullscreen mode

Agora vamos transicionar nossa 承诺 para os dois valores conhecidos, FULFILLEDe REJECTED:

import { PromiseStates, ResolveFunction, RejectFunction, ExecutorFunction, Nullable, Thennable, HandlerFunction } from './PromiseTypes'

export class TypePromise {
  private state: PromiseStates = PromiseStates.PENDING
  private value: any = null
  private thenHandlers: HandlerFunction[] = []

  private fulfill (value: any) {
    this.state = PromiseStates.FULFILLED
    this.value = value
  }

  private reject (reason: any) {
    this.state = PromiseStates.REJECTED
    this.value = reason
  }
}
Enter fullscreen mode Exit fullscreen mode

我只是想改变国家的情况。 São eles que vão Finalizar uma Promise and Setar seu Valor Final。

瓦莫斯·阿戈拉(Vamosagora)说,我们在履行承诺的过程resolve中做出了回应,并做出了回应,并决定了解决或拒绝的方式,这是我们所承诺的承诺。

import { PromiseStates, ResolveFunction, RejectFunction, ExecutorFunction, Nullable, Thennable, HandlerFunction } from './PromiseTypes'

export class TypePromise {
  private state: PromiseStates = PromiseStates.PENDING
  private value: any = null
  private thenHandlers: HandlerFunction[] = []

  private fulfill (value: any) {
    this.state = PromiseStates.FULFILLED
    this.value = value
  }

  private reject (reason: any) {
    this.state = PromiseStates.REJECTED
    this.value = reason
  }

  private resolve (result: any) {
    try {
        const then = this.getThen(result)
        if (then) return this.doResolve(then.bind(result), this.resolve, this.reject)
        this.fulfill(result)
    } catch (error) {
        this.reject(error)
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

我们的resolve基本功能是对所要求的对象作出响应,并获得所收到的对象的功能thennable,这是一种新的功能,是doResolve执行人的职责,是执行人的代理权,是我们内部承诺的方法,是的我是一个承诺,我们承诺,我们会做出回应,我们可能会在内部做出承诺,我们承诺,但我们不会承诺。 Vamos 执行了最初的操作getThen,但对额外的响应或忽略了功能thennable

import { PromiseStates, ResolveFunction, RejectFunction, ExecutorFunction, Nullable, Thennable, HandlerFunction } from './PromiseTypes'

export class TypePromise {
  private state: PromiseStates = PromiseStates.PENDING
  private value: any = null
  private thenHandlers: HandlerFunction[] = []

  private fulfill (value: any) {
    this.state = PromiseStates.FULFILLED
    this.value = value
  }

  private reject (reason: any) {
    this.state = PromiseStates.REJECTED
    this.value = reason
  }

  private resolve (result: any) {
    try {
        const then = this.getThen(result)
        if (then) return this.doResolve(then.bind(result), this.resolve, this.reject)
        this.fulfill(result)
    } catch (error) {
        this.reject(error)
    }
  }

  private getThen (value: Thennable) {
    const valueType = typeof value
    if (value && (valueType === 'object' || valueType === 'function')) {
      const then = value.then
      if (typeof then === 'function') return then
    }
    return null
  }
}
Enter fullscreen mode Exit fullscreen mode

功能很简单,接收对象thennable并验证其勇气,并验证对象或功能,然后将其验证为正确的属性,then然后将其重新设置为处理程序的一部分。

Vamos para o método doResolve,ele é o método 主要承诺,porque é que vai iniciar toda a cadia 。 Sendo 响应以保证执行和编辑包装器的功能,并重新编辑内部控制的功能。

import { 
  PromiseStates, 
  ResolveFunction, 
  RejectFunction, 
  ExecutorFunction, 
  Nullable, 
  Thennable, 
  HandlerFunction 
} from './PromiseTypes'

enum ReturnType {
  SUCCESS = 'success',
  ERROR = 'error'
}

export class TypePromise {
  private state: PromiseStates = PromiseStates.PENDING
  private value: any = null
  private thenHandlers: HandlerFunction[] = []

  private fulfill (value: any) {
    this.state = PromiseStates.FULFILLED
    this.value = value
  }

  private reject (reason: any) {
    this.state = PromiseStates.REJECTED
    this.value = reason
  }

  private resolve (result: any) {
    try {
        const then = this.getThen(result)
        if (then) return this.doResolve(then.bind(result), this.resolve, this.reject)
        this.fulfill(result)
    } catch (error) {
        this.reject(error)
    }
  }

  private getThen (value: Thennable) {
    const valueType = typeof value
    if (value && (valueType === 'object' || valueType === 'function')) {
      const then = value.then
      if (typeof then === 'function') return then
    }
    return null
  }

  private getHandlerType (type: ReturnType, done: boolean, onFulfilled: ResolveFunction, onRejected: RejectFunction) {
    return (value: any) => {
      if (done) return
      done = true
      return { error: onRejected, success: onFulfilled }[type](value)
    }
  }

  private doResolve (resolverFn: ExecutorFunction, onFulfilled: ResolveFunction, onRejected: RejectFunction) {
    let done = false
    try {
            resolverFn(this.getHandlerType(ReturnType.SUCCESS, done, onFulfilled, onRejected), this.getHandlerType(ReturnType.ERROR, done, onFulfilled, onRejected))
    } catch (error) {
      if (done) return
      done = true
      onRejected(error)
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

Agora fizemos algumas coisas a mais。最初的功能doResolve是执行程序的基本功能,您可以通过 Criando 包装器重新编辑内部功能,并在执行过程中执行一些操作,这是我们的功能getHandlerType,基本功能,新的功能função com assinatura (value: any)com uma checagem se ela já foi ou não executada alguma vez。 Se sim, apenas retornamos, se não, vamos pegar aspectiva função de acordo com o Tipo que queremos – ela pode ser uma função de resolução de rejeição, para fazer isso criamos no topo do arquivo or enum interno ReturnType– e vamo executá-la retornando seu valor.

目前,如果我们无法改变承诺的解决方案,那么我们就必须解决承诺问题。在此,请按照以下方法进行操作executeHandler,对接收和执行对象做出响应,并执行一系列处理程序和执行待办事项的HandlerFunction辅助功能:executeAllHandlers

import { 
  PromiseStates, 
  ResolveFunction, 
  RejectFunction, 
  ExecutorFunction, 
  Nullable, 
  Thennable, 
  HandlerFunction 
} from './PromiseTypes'

enum ReturnType {
  SUCCESS = 'success',
  ERROR = 'error'
}

export class TypePromise {
  private state: PromiseStates = PromiseStates.PENDING
  private value: any = null
  private thenHandlers: HandlerFunction[] = []

  private fulfill (value: any) {
    this.state = PromiseStates.FULFILLED
    this.value = value
        this.executeAllHandlers()
  }

  private reject (reason: any) {
    this.state = PromiseStates.REJECTED
    this.value = reason
    this.executeAllHandlers()
  }

  private executeAllHandlers () {
    this.thenHandlers.forEach(this.executeHandler)
    this.thenHandlers = []  
  }

  private executeHandler (handler: HandlerFunction) {
    if (this.state === PromiseStates.PENDING) return this.thenHandlers.push(handler)
    if (this.state === PromiseStates.FULFILLED && typeof handler.onFulfilled === 'function') return handler.onFulfilled(this.value)
    if (this.state === PromiseStates.REJECTED && typeof handler.onRejected === 'function') return handler.onRejected(this.value)
  }

  private resolve (result: any) {
    try {
        const then = this.getThen(result)
        if (then) return this.doResolve(then.bind(result), this.resolve, this.reject)
        this.fulfill(result)
    } catch (error) {
        this.reject(error)
    }
  }

  private getThen (value: Thennable) {
    const valueType = typeof value
    if (value && (valueType === 'object' || valueType === 'function')) {
      const then = value.then
      if (typeof then === 'function') return then
    }
    return null
  }

  private getHandlerType (type: ReturnType, done: boolean, onFulfilled: ResolveFunction, onRejected: RejectFunction) {
    return (value: any) => {
      if (done) return
      done = true
      return { error: onRejected, success: onFulfilled }[type](value)
    }
  }

  private doResolve (resolverFn: ExecutorFunction, onFulfilled: ResolveFunction, onRejected: RejectFunction) {
    let done = false
    try {
            resolverFn(this.getHandlerType(ReturnType.SUCCESS, done, onFulfilled, onRejected), this.getHandlerType(ReturnType.ERROR, done, onFulfilled, onRejected))
    } catch (error) {
      if (done) return
      done = true
      onRejected(error)
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

Com isso terminamos nossa máquina de estados。

Expondo 方法

Já que acabamos de construir nossa máquina de estados e suas transições, vamos agora criar os métodos que vão poder ser executados pelo usuário, como o then, catche 等。

import { 
  PromiseStates, 
  ResolveFunction, 
  RejectFunction, 
  ExecutorFunction, 
  Nullable, 
  Thennable, 
  HandlerFunction 
} from './PromiseTypes'

enum ReturnType {
  SUCCESS = 'success',
  ERROR = 'error'
}

export class TypePromise {
  private state: PromiseStates = PromiseStates.PENDING
  private value: any = null
  private thenHandlers: HandlerFunction[] = []

  constructor (executor: ExecutorFunction) {
    this.resolve = this.resolve.bind(this)
    this.reject = this.reject.bind(this)
    this.executeHandler = this.executeHandler.bind(this)
    this.doResolve(executor, this.resolve, this.reject)
  }

  private fulfill (value: any) {
    this.state = PromiseStates.FULFILLED
    this.value = value
        this.executeAllHandlers()
  }

  private reject (reason: any) {
    this.state = PromiseStates.REJECTED
    this.value = reason
    this.executeAllHandlers()
  }

  private executeAllHandlers () {
    this.thenHandlers.forEach(this.executeHandler)
    this.thenHandlers = []  
  }

  private executeHandler (handler: HandlerFunction) {
    if (this.state === PromiseStates.PENDING) return this.thenHandlers.push(handler)
    if (this.state === PromiseStates.FULFILLED && typeof handler.onFulfilled === 'function') return handler.onFulfilled(this.value)
    if (this.state === PromiseStates.REJECTED && typeof handler.onRejected === 'function') return handler.onRejected(this.value)
  }

  private resolve (result: any) {
    try {
        const then = this.getThen(result)
        if (then) return this.doResolve(then.bind(result), this.resolve, this.reject)
        this.fulfill(result)
    } catch (error) {
        this.reject(error)
    }
  }

  private getThen (value: Thennable) {
    const valueType = typeof value
    if (value && (valueType === 'object' || valueType === 'function')) {
      const then = value.then
      if (typeof then === 'function') return then
    }
    return null
  }

  private getHandlerType (type: ReturnType, done: boolean, onFulfilled: ResolveFunction, onRejected: RejectFunction) {
    return (value: any) => {
      if (done) return
      done = true
      return { error: onRejected, success: onFulfilled }[type](value)
    }
  }

  private doResolve (resolverFn: ExecutorFunction, onFulfilled: ResolveFunction, onRejected: RejectFunction) {
    let done = false
    try {
            resolverFn(this.getHandlerType(ReturnType.SUCCESS, done, onFulfilled, onRejected), this.getHandlerType(ReturnType.ERROR, done, onFulfilled, onRejected))
    } catch (error) {
      if (done) return
      done = true
      onRejected(error)
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

我们只需简单地设置一些初始值和功能doResolve,并开始解决承诺。

观察价值

观察我们的承诺then,成功,或catch错误。 Vamos criar nosso primeiro método público then:

import { 
  PromiseStates, 
  ResolveFunction, 
  RejectFunction, 
  ExecutorFunction, 
  Nullable, 
  Thennable, 
  HandlerFunction 
} from './PromiseTypes'

enum ReturnType {
  SUCCESS = 'success',
  ERROR = 'error'
}

export class TypePromise {
  private state: PromiseStates = PromiseStates.PENDING
  private value: any = null
  private thenHandlers: HandlerFunction[] = []

  constructor (executor: ExecutorFunction) {
    this.resolve = this.resolve.bind(this)
    this.reject = this.reject.bind(this)
    this.executeHandler = this.executeHandler.bind(this)
    this.doResolve(executor, this.resolve, this.reject)
  }

  private fulfill (value: any) {
    this.state = PromiseStates.FULFILLED
    this.value = value
        this.executeAllHandlers()
  }

  private reject (reason: any) {
    this.state = PromiseStates.REJECTED
    this.value = reason
    this.executeAllHandlers()
  }

  private executeAllHandlers () {
    this.thenHandlers.forEach(this.executeHandler)
    this.thenHandlers = []  
  }

  private executeHandler (handler: HandlerFunction) {
    if (this.state === PromiseStates.PENDING) return this.thenHandlers.push(handler)
    if (this.state === PromiseStates.FULFILLED && typeof handler.onFulfilled === 'function') return handler.onFulfilled(this.value)
    if (this.state === PromiseStates.REJECTED && typeof handler.onRejected === 'function') return handler.onRejected(this.value)
  }

  private resolve (result: any) {
    try {
        const then = this.getThen(result)
        if (then) return this.doResolve(then.bind(result), this.resolve, this.reject)
        this.fulfill(result)
    } catch (error) {
        this.reject(error)
    }
  }

  private getThen (value: Thennable) {
    const valueType = typeof value
    if (value && (valueType === 'object' || valueType === 'function')) {
      const then = value.then
      if (typeof then === 'function') return then
    }
    return null
  }

  private getHandlerType (type: ReturnType, done: boolean, onFulfilled: ResolveFunction, onRejected: RejectFunction) {
    return (value: any) => {
      if (done) return
      done = true
      return { error: onRejected, success: onFulfilled }[type](value)
    }
  }

  private doResolve (resolverFn: ExecutorFunction, onFulfilled: ResolveFunction, onRejected: RejectFunction) {
    let done = false
    try {
            resolverFn(this.getHandlerType(ReturnType.SUCCESS, done, onFulfilled, onRejected), this.getHandlerType(ReturnType.ERROR, done, onFulfilled, onRejected))
    } catch (error) {
      if (done) return
      done = true
      onRejected(error)
    }
  }

  then (onFulfilled?: ResolveFunction, onRejected?: Nulable<RejectFunction>): TypePromise {
    return new TypePromise((resolve: ResolveFunction, reject: RejectFunction) => {
      const handleResult = (type: ReturnType) => {
        return (result: any) => {
          try {
            const executorFunction = type === ReturnType.ERROR ? reject : resolve
            const checkFunction = type === ReturnType.ERROR ? onRejected : onFulfilled
            return (typeof checkFunction === 'function') ? executorFunction(checkFunction(result)) : executorFunction(result)
          } catch (error) {
            reject(error)
          }
        }
      }

      return this.done(handleResult(ReturnType.SUCCESS), handleResult(ReturnType.ERROR))
    })
  }
}
Enter fullscreen mode Exit fullscreen mode

执行前面的方法then,执行选项参数并返回新承诺的实例。新应用程序使用哈希图技术来选择作为服务执行的函数。作为函数传递的函数、函数、函数、执行器是最初的函数和执行器的结果最终的解析器是一个承诺,如果不,执行器将执行一个函数rejectresolveVeja que temos um novo método, o done

做事的语义done(onFulfilled, onRejected)很简单,我们可以then使用其他方式来确定一个承诺。一个 função donesegue as seguintes regras:

  • 一些参数和查马多
  • Só pode ser chamada uma vez

该功能是为了tick确保执行的事件循环没有最终执行而确定的。可以使用 APIprocess.nextTick来执行 Node 中微任务的功能(这是最重要的),并且永远不会最终执行事件循环:

import { 
  PromiseStates, 
  ResolveFunction, 
  RejectFunction, 
  ExecutorFunction, 
  Nullable, 
  Thennable, 
  HandlerFunction 
} from './PromiseTypes'

enum ReturnType {
  SUCCESS = 'success',
  ERROR = 'error'
}

export class TypePromise {
  private state: PromiseStates = PromiseStates.PENDING
  private value: any = null
  private thenHandlers: HandlerFunction[] = []

  constructor (executor: ExecutorFunction) {
    this.resolve = this.resolve.bind(this)
    this.reject = this.reject.bind(this)
    this.executeHandler = this.executeHandler.bind(this)
    this.doResolve(executor, this.resolve, this.reject)
  }

  private fulfill (value: any) {
    this.state = PromiseStates.FULFILLED
    this.value = value
        this.executeAllHandlers()
  }

  private reject (reason: any) {
    this.state = PromiseStates.REJECTED
    this.value = reason
    this.executeAllHandlers()
  }

  private executeAllHandlers () {
    this.thenHandlers.forEach(this.executeHandler)
    this.thenHandlers = []  
  }

  private executeHandler (handler: HandlerFunction) {
    if (this.state === PromiseStates.PENDING) return this.thenHandlers.push(handler)
    if (this.state === PromiseStates.FULFILLED && typeof handler.onFulfilled === 'function') return handler.onFulfilled(this.value)
    if (this.state === PromiseStates.REJECTED && typeof handler.onRejected === 'function') return handler.onRejected(this.value)
  }

  private resolve (result: any) {
    try {
        const then = this.getThen(result)
        if (then) return this.doResolve(then.bind(result), this.resolve, this.reject)
        this.fulfill(result)
    } catch (error) {
        this.reject(error)
    }
  }

  private getThen (value: Thennable) {
    const valueType = typeof value
    if (value && (valueType === 'object' || valueType === 'function')) {
      const then = value.then
      if (typeof then === 'function') return then
    }
    return null
  }

  private getHandlerType (type: ReturnType, done: boolean, onFulfilled: ResolveFunction, onRejected: RejectFunction) {
    return (value: any) => {
      if (done) return
      done = true
      return { error: onRejected, success: onFulfilled }[type](value)
    }
  }

  private doResolve (resolverFn: ExecutorFunction, onFulfilled: ResolveFunction, onRejected: RejectFunction) {
    let done = false
    try {
            resolverFn(this.getHandlerType(ReturnType.SUCCESS, done, onFulfilled, onRejected), this.getHandlerType(ReturnType.ERROR, done, onFulfilled, onRejected))
    } catch (error) {
      if (done) return
      done = true
      onRejected(error)
    }
  }

  then (onFulfilled?: ResolveFunction, onRejected?: Nulable<RejectFunction>): TypePromise {
    return new TypePromise((resolve: ResolveFunction, reject: RejectFunction) => {
      const handleResult = (type: ReturnType) => {
        return (result: any) => {
          try {
            const executorFunction = type === ReturnType.ERROR ? reject : resolve
            const checkFunction = type === ReturnType.ERROR ? onRejected : onFulfilled
            return (typeof checkFunction === 'function') ? executorFunction(checkFunction(result)) : executorFunction(result)
          } catch (error) {
            reject(error)
          }
        }
      }

      return this.done(handleResult(ReturnType.SUCCESS), handleResult(ReturnType.ERROR))
    })
  }

  private done (onFulfilled?: ResolveFunction, onRejected?: Nullable<RejectFunction>) {
    process.nextTick(() => {
      this.executeHandler({
        onFulfilled,
        onRejected
      })
    })
  }
}
Enter fullscreen mode Exit fullscreen mode

执行该处理程序的方法是直接执行,无需then最后勾选。

抓住

最后,请执行我们的方法catch,以捕获承诺的错误。 Ele é bastante simples and também tira proito da função done, differenteentemente do then, o catch semper terá um argumento cujo Tipo uma função de rejeição:

import { 
  PromiseStates, 
  ResolveFunction, 
  RejectFunction, 
  ExecutorFunction, 
  Nullable, 
  Thennable, 
  HandlerFunction 
} from './PromiseTypes'

enum ReturnType {
  SUCCESS = 'success',
  ERROR = 'error'
}

export class TypePromise {
  private state: PromiseStates = PromiseStates.PENDING
  private value: any = null
  private thenHandlers: HandlerFunction[] = []

  constructor (executor: ExecutorFunction) {
    this.resolve = this.resolve.bind(this)
    this.reject = this.reject.bind(this)
    this.executeHandler = this.executeHandler.bind(this)
    this.doResolve(executor, this.resolve, this.reject)
  }

  private fulfill (value: any) {
    this.state = PromiseStates.FULFILLED
    this.value = value
        this.executeAllHandlers()
  }

  private reject (reason: any) {
    this.state = PromiseStates.REJECTED
    this.value = reason
    this.executeAllHandlers()
  }

  private executeAllHandlers () {
    this.thenHandlers.forEach(this.executeHandler)
    this.thenHandlers = []  
  }

  private executeHandler (handler: HandlerFunction) {
    if (this.state === PromiseStates.PENDING) return this.thenHandlers.push(handler)
    if (this.state === PromiseStates.FULFILLED && typeof handler.onFulfilled === 'function') return handler.onFulfilled(this.value)
    if (this.state === PromiseStates.REJECTED && typeof handler.onRejected === 'function') return handler.onRejected(this.value)
  }

  private resolve (result: any) {
    try {
        const then = this.getThen(result)
        if (then) return this.doResolve(then.bind(result), this.resolve, this.reject)
        this.fulfill(result)
    } catch (error) {
        this.reject(error)
    }
  }

  private getThen (value: Thennable) {
    const valueType = typeof value
    if (value && (valueType === 'object' || valueType === 'function')) {
      const then = value.then
      if (typeof then === 'function') return then
    }
    return null
  }

  private getHandlerType (type: ReturnType, done: boolean, onFulfilled: ResolveFunction, onRejected: RejectFunction) {
    return (value: any) => {
      if (done) return
      done = true
      return { error: onRejected, success: onFulfilled }[type](value)
    }
  }

  private doResolve (resolverFn: ExecutorFunction, onFulfilled: ResolveFunction, onRejected: RejectFunction) {
    let done = false
    try {
            resolverFn(this.getHandlerType(ReturnType.SUCCESS, done, onFulfilled, onRejected), this.getHandlerType(ReturnType.ERROR, done, onFulfilled, onRejected))
    } catch (error) {
      if (done) return
      done = true
      onRejected(error)
    }
  }

  then (onFulfilled?: ResolveFunction, onRejected?: Nulable<RejectFunction>): TypePromise {
    return new TypePromise((resolve: ResolveFunction, reject: RejectFunction) => {
      const handleResult = (type: ReturnType) => {
        return (result: any) => {
          try {
            const executorFunction = type === ReturnType.ERROR ? reject : resolve
            const checkFunction = type === ReturnType.ERROR ? onRejected : onFulfilled
            return (typeof checkFunction === 'function') ? executorFunction(checkFunction(result)) : executorFunction(result)
          } catch (error) {
            reject(error)
          }
        }
      }

      return this.done(handleResult(ReturnType.SUCCESS), handleResult(ReturnType.ERROR))
    })
  }

  private done (onFulfilled?: ResolveFunction, onRejected?: Nullable<RejectFunction>) {
    process.nextTick(() => {
      this.executeHandler({
        onFulfilled,
        onRejected
      })
    })
  }

  catch (onRejected: RejectFunction) {
    return new TypePromise((resolve: ResolveFunction, reject: RejectFunction) => {
      return this.done(resolve, (error: any) => {
        if(typeof onRejected === 'function') {
          try {
            return resolve(onRejected(error))
          } catch (error) {
            reject(error)
          }
        }
        return reject(error)
      })
    })
  }
}
Enter fullscreen mode Exit fullscreen mode

重新启动新星承诺并验证其功能,而不是承诺之前的解析器承诺。

额外内容:最后

promise.prototype.finally算法节奏是ES6 的活力和功能的具体体现。finally一个简单的目标:Assim como o finallyque temos em um bloco try/catch,o finallyde uma Promise é semper executado no Final de sua resolução,independente se a Promise foi resolvida or rejeitada,porém,differentemente dos observadores como thene catch,ofinal não retorna outra proment então não可能已经完成了任务或最终被执行。

一个相对简单的工具,可以让您在诺萨承诺查马达中获得财产finalFunction,并获得乐趣。套针的目的和方法finally是使用功能和执行方法的,没有最终方法fulfillreject

import { 
  PromiseStates, 
  ResolveFunction, 
  RejectFunction, 
  ExecutorFunction, 
  Nullable, 
  Thennable, 
  HandlerFunction 
} from './PromiseTypes'

enum ReturnType {
  SUCCESS = 'success',
  ERROR = 'error'
}

export class TypePromise {
  private state: PromiseStates = PromiseStates.PENDING
  private finalFunction: Function = () => { }
  private value: any = null
  private thenHandlers: HandlerFunction[] = []

  constructor (executor: ExecutorFunction) {
    this.resolve = this.resolve.bind(this)
    this.reject = this.reject.bind(this)
    this.executeHandler = this.executeHandler.bind(this)
    this.doResolve(executor, this.resolve, this.reject)
  }

  private fulfill (value: any) {
    this.state = PromiseStates.FULFILLED
    this.value = value
        this.executeAllHandlers()
    this.finalFunction() // Executamos o finally
  }

  private reject (reason: any) {
    this.state = PromiseStates.REJECTED
    this.value = reason
    this.executeAllHandlers()
    this.finalFunction() // Executamos o finally
  }

  private executeAllHandlers () {
    this.thenHandlers.forEach(this.executeHandler)
    this.thenHandlers = []  
  }

  private executeHandler (handler: HandlerFunction) {
    if (this.state === PromiseStates.PENDING) return this.thenHandlers.push(handler)
    if (this.state === PromiseStates.FULFILLED && typeof handler.onFulfilled === 'function') return handler.onFulfilled(this.value)
    if (this.state === PromiseStates.REJECTED && typeof handler.onRejected === 'function') return handler.onRejected(this.value)
  }

  private resolve (result: any) {
    try {
        const then = this.getThen(result)
        if (then) return this.doResolve(then.bind(result), this.resolve, this.reject)
        this.fulfill(result)
    } catch (error) {
        this.reject(error)
    }
  }

  private getThen (value: Thennable) {
    const valueType = typeof value
    if (value && (valueType === 'object' || valueType === 'function')) {
      const then = value.then
      if (typeof then === 'function') return then
    }
    return null
  }

  private getHandlerType (type: ReturnType, done: boolean, onFulfilled: ResolveFunction, onRejected: RejectFunction) {
    return (value: any) => {
      if (done) return
      done = true
      return { error: onRejected, success: onFulfilled }[type](value)
    }
  }

  private doResolve (resolverFn: ExecutorFunction, onFulfilled: ResolveFunction, onRejected: RejectFunction) {
    let done = false
    try {
            resolverFn(this.getHandlerType(ReturnType.SUCCESS, done, onFulfilled, onRejected), this.getHandlerType(ReturnType.ERROR, done, onFulfilled, onRejected))
    } catch (error) {
      if (done) return
      done = true
      onRejected(error)
    }
  }

  then (onFulfilled?: ResolveFunction, onRejected?: Nulable<RejectFunction>): TypePromise {
    return new TypePromise((resolve: ResolveFunction, reject: RejectFunction) => {
      const handleResult = (type: ReturnType) => {
        return (result: any) => {
          try {
            const executorFunction = type === ReturnType.ERROR ? reject : resolve
            const checkFunction = type === ReturnType.ERROR ? onRejected : onFulfilled
            return (typeof checkFunction === 'function') ? executorFunction(checkFunction(result)) : executorFunction(result)
          } catch (error) {
            reject(error)
          }
        }
      }

      return this.done(handleResult(ReturnType.SUCCESS), handleResult(ReturnType.ERROR))
    })
  }

  private done (onFulfilled?: ResolveFunction, onRejected?: Nullable<RejectFunction>) {
    process.nextTick(() => {
      this.executeHandler({
        onFulfilled,
        onRejected
      })
    })
  }

  catch (onRejected: RejectFunction) {
    return new TypePromise((resolve: ResolveFunction, reject: RejectFunction) => {
      return this.done(resolve, (error: any) => {
        if(typeof onRejected === 'function') {
          try {
            return resolve(onRejected(error))
          } catch (error) {
            reject(error)
          }
        }
        return reject(error)
      })
    })
  }

  finally (finalFunction: Function) {
    if (typeof finalFunction === 'function') this.finalFunction = finalFunction
  }
}
Enter fullscreen mode Exit fullscreen mode

结论

Criamos nossa própria 实现了 Typescript 的功能。这是一个有利的开发节奏,在执行功能、最后、以及在构建消息时执行 JavaScript 的所有任务和转换过程中,您可以快速地完成这些任务。我们国家力量承诺:

import { TypePromise } from './TypePromise'

function foo (param: any) {
  return new TypePromise((resolve, reject) => {
    if (Math.random() > 0.5) return setTimeout(resolve, 1000, param)
    return setTimeout(reject, 1000, 'error')
  })
}

(() => {
  foo(5)
    .then((value) => console.log(value))
    .catch((error) => console.error(error))
    .finally(() => console.log('aways return'))
})()
Enter fullscreen mode Exit fullscreen mode

请注意any,在各种情况下,您都可以使用 Typescript 来使用 Typescript。 Então,como uma lição de casa,um desafio bacana seria Implementar os Tipos generics para que class TypePromisepasse a ser class TypePromise<T>。 Vamos abordar essa correção na Sequencia deste artigo!

如果您有兴趣,请参考以下内容:

您可以继续阅读我的博客添加新闻通讯来接收最新消息!

文章来源:https://dev.to/_staticvoid/construindo-uma-promise-do-zero-4ndp