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
promise调用方法如下
const p1 = new Promise(function(resolve,reject){ resolve('success1'); resolve('success2'); }); p1.then(function(value){ console.log(value); // success1 });
class Promise{ constructor(executor){ //初始化state为等待态 this.state = 'pending'; //成功的值 this.value = undefined; //失败的值 this.reason = undefined; //将then里的函数存放在数组中 this.onResoledCallbacks = [];//存放成功的数组 this.onRejectedCallbacks = [];//存放失败的数组 let resolve = value=>{ if(this.state === 'pending'){ this.state = 'fulfilled'; this.value = value; //一旦resolve执行,调用成功数组的函数 this.onResoledCallbacks.forEach(fn=>fn()); } }; let reject = reason=>{ if(this.state ==='pending'){ this.state = 'rejected'; this.reason = reason; //一旦reject执行,调用失败数组的函数 this.onRejectedCallbacks.forEach(fn=>fn()); } }; try{ executor(resolve,reject); }catch(err){ reject(err); } } then(onFulfilled,onRejected){ let promise2 = new Promise((resolve,reject)=>{ if(this.state === 'fulfilled'){ let x = onFulfilled(this.value); //resovePromise函数,处理自己return的promise和默认的promise的关系 resolvePromise(promise2,x,resolve,reject); } if(this.state === 'rejected') { let x = onRejected(this.reason); resolvePromise(promise2,x,resolve,reject); } if(this.state ==='pending'){ this.onResoledCallbacks.push(()=>{//解决异步问题 let x = onFulfilled(this.value); resolvePromise(promise2,x,resolve,reject); }) this.onRejectedCallbacks.push(()=>{ let x = onRejected(this.reason); resolvePromise(promise2,x,resolve,reject); }) } }) return promise2;//解决链式回调问题 } }
未完。。。。。。。。
还有太多未理解未完成的地方
此文参考 https://juejin.im/entry/5b32f7026fb9a00e883f351b
The text was updated successfully, but these errors were encountered:
No branches or pull requests
重写Promise
promise调用方法如下
那promise内部是如何实现的呢?
代码
未完。。。。。。。。
还有太多未理解未完成的地方
此文参考 https://juejin.im/entry/5b32f7026fb9a00e883f351b
The text was updated successfully, but these errors were encountered: