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 { static PENDING = '待定'; static FULFILLED = '成功'; static REJECTED = '失败'; constructor(func){ console.log('construtor') this.status = myPromise.PENDING; this.result = null; this.resolveCallbacks = []; // 处理 then里面也是异步函数;也是说处于 pending状态的函数, 保存回调的函数 this.rejectCallbacks = []; try { func(this.resolve.bind(this),this.reject.bind(this)) // 构造函数, 执行传入函数 ,支持处理 resolve,reject } catch (error) { this.reject(error) // 这里不用bind了 , 因为是直接执行,不是创建实例后才执行. 需要bind是创建实例后,this也要继承父实例的 不然父类找到方法/属性 } } resolve(result){ console.log('resolve') setTimeout(()=>{ // 末尾执行 console.log('resolve--settimeout') if(this.status === myPromise.PENDING){ this.status = myPromise.FULFILLED; this.result = result } this.resolveCallbacks.forEach(callback => { callback(result) }) }) } reject(result){ console.log('reject') setTimeout(()=>{ // 末尾执行 console.log('reject--setTimeout') if(this.status === myPromise.PENDING){ this.status = myPromise.REJECTED; this.result = result } this.rejectCallbacks.forEach(callback => { callback(result) }) }) } then(onFULFILLED,onREDJECTED){ return new myPromise((resolve,reject)=>{ // 返回promise 链式调用 // 根据标准,如果then的参数不是function,则我们需要忽略它,此处以如下方式处理 // 值的穿透 (只不过是then默认参数就是把值往后传或者抛) onFULFILLED = typeof onFULFILLED === 'function' ? onFULFILLED : () => {}; onREDJECTED = typeof onREDJECTED === 'function' ? onREDJECTED : () => {}; if(this.status === myPromise.PENDING){ // 处理等待状态的函数 ,例如 异步函数 this.resolveCallbacks.push(onFULFILLED) this.rejectCallbacks.push(onREDJECTED) } if(this.status === myPromise.FULFILLED){ setTimeout(() =>{ onFULFILLED(this.result) }) } if(this.status === myPromise.REJECTED){ setTimeout(() =>{ onREDJECTED(this.result) }) } }) } }
参考 : https://www.bilibili.com/video/BV1RR4y1p7my/?spm_id_from=333.788
// 面试常考点 // 从如何停掉 Promise 链说起 // xieranmaya/blog#5
// 实现有并行限制的Promise调度器 // https://juejin.im/post/6854573217013563405 // 维护一个 放promise 的 queue 队列
// 实现promise.all 方法 count 记录执行成功的数量 与传入的promise列表长度一致 为成功输出 https://juejin.cn/post/7069805387490263047
The text was updated successfully, but these errors were encountered:
No branches or pull requests
promise 简易实现
参考 : https://www.bilibili.com/video/BV1RR4y1p7my/?spm_id_from=333.788
// 面试常考点
// 从如何停掉 Promise 链说起
// xieranmaya/blog#5
// 实现有并行限制的Promise调度器
// https://juejin.im/post/6854573217013563405
// 维护一个 放promise 的 queue 队列
// 实现promise.all 方法
count 记录执行成功的数量 与传入的promise列表长度一致 为成功输出
https://juejin.cn/post/7069805387490263047
The text was updated successfully, but these errors were encountered: