手写代码 -- Promise
这里只实现了一个简单的Promise,更加完善的Promise实现请参照 Promises/A+ 标准
class _Promise { constructor(fn) { this.state = "pendding"; this.value = undefined; this.resolvedCallback = []; this.rejectedCallback = []; fn(this.resolve.bind(this), this.reject.bind(this)) } resolve(value) { if (this.state == "pendding") { this.state = "resolved"; this.value = value; this.resolvedCallback.forEach(fn => fn(this.value)) } } reject(value) { if (this.state == "pendding") { this.state = "rejected"; this.value = value; this.rejectedCallback.forEach(fn => fn(this.value)) } } then(resolve = () => {}, reject = () => {}) { if (this.state == "pendding") { this.resolvedCallback.push(resolve) this.rejectedCallback.push(reject) } if (this.state == "resolved") { resolve(this.value) } if (this.state == "rejected") { reject(this.value) } } }
简单的测试一下
new _Promise((resolve, reject) => { setTimeout(()=>{ resolve("hello") }, 2000) }).then(res => { console.log(res) }, err => { console.log("err", err) })