We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
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
class MyPromise { constructor(fn) { if (!fn || typeof(fn) !== 'function') { throw new Error('需要传入函数作为参数') } this.state = 'pending' // 初始化状态 this.value = null // resolve成功的值 this.reason = null // reject失败的值 this.resolveCallbacks = [] // 存放成功的回调数组 this.rejectCallbacks = [] // 存放失败的回调数组 const resolve = value => { if (this.state === 'pending') { this.state = 'fulfilled' this.value = value; this.resolveCallbacks.forEach(cb => cb(value)) } } const reject = reason => { if (this.state === 'pending') { this.state = 'rejected' this.reason = reason this.rejectCallbacks.forEach(cb => cb(reason)) } } try{ fn(resolve, reject) } catch (err) { reject(err) } } then(onResolve, onReject) { onResolve = typeof(onResolve) === 'function' ? onResolve : value => value; onReject = typeof(onReject) === 'function' ? onReject : reason => reason; switch(this.state) { // resolve或者reject在异步函数中执行时,state还是pendding状态,将他们的回调处理函数先保存,一旦resolve或者reject时,就调用 case 'pending': this.resolveCallbacks.push(onResolve); // 将成功的回调存到resolveCallbacks里面 this.rejectCallbacks.push(onReject) // 将失败的回调存到rejectCallbacks里面 break; case 'fulfilled': onResolve(this.value) break; case 'rejected': onReject(this.reason) break; } } }
The text was updated successfully, but these errors were encountered:
No branches or pull requests
手动实现一个Promise
Promise简单说明
实现思路
以下是实现代码
The text was updated successfully, but these errors were encountered: