day107-typescript实现promise

前言

最近某个babel的项目的时候接触到了typescript,感觉这个世界还是静态语言的天下啊。赶紧学起来。当然学静态语言,单元测试也是很重要的一部分。但是这个过程看来有点漫长,慢慢来吧。本文主要是笔记,看别人怎么实现promisejs。先看看实现promise标准和比较完美的Bluebird方案
这篇文章有点扯,只是写了一部分,并没有写完全。0.0


实现(部分)

接口

type HandlerOnSuccess<T, U = any> = (value: T) => U | Thenable<U>;
type HandlerOnFail<U = any> = (reason: any) => U | Thenable<U>;

interface Handler<T, U> {
onSuccess: HandlerOnSuccess<T, U>;
onFail: HandlerOnFail<U>;
}

构造器等

class PQ<T> {
private state: States = States.PENDING
private handlers: Handler<T, any>[] = []
private value: T | any
public static errors = errors
// 构造器constructor
public constructor(callback: (resolve: Resolve<T>, reject: Reject) => void) {
try {
// 回调参数this.resolve,this.reject
callback(this.resolve, this.reject)
} catch (error) {
this.reject(error)
}
}

private setResult = (value: T | any, state: States) => {
const set = () => {
if (this.state !== States.PENDING) {
return null
}
if (isThenable(value)) {
return (value as Thenable<T>).then(this.resolve, this.reject)
}
this.value = value
this.state = state

return this.executeHandlers()
}
setTimeout(set, 0)
}
}

参考

Implementing Promises In JavaScript

文章作者: lmislm
文章链接: http://lmislm.com/2019/04/29/2019-04-29/
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 LMISLMのBlog