手写Promise自定义封装 then 函数
Promise 自定义封装 then 函数
<script src="./Promise.js"></script>
<script type="text/javascript">
let p = new Promise((resolve, reject) => {
resolve('ok');
})
p.then(res => {
console.log('res', res)
}, err => {
console.log(err)
})
</script>
我们现在发现,then方法中压根就没有输出内容;
是因为我们对then函数没有进行封装;
所以现在我们需要对then函数进行一次封装了
怎么封装了???????????、
31 自定义封装 then 方法执行回调
function Promise(executor){
const self=this;
function resolve(data){
// 如果状态发生改变就直接返回(为了让Promise的状态只发生一次改变);
if( self.PromiseStatus!=='pending') return
self.PromiseStatus='resolved';
self.PromiseValue=data;
}
// 同样声明成为一个函数;修改状态
function reject(err){
// 如果状态发生改变就直接返回(为了让Promise的状态只发生一次改变);
if( self.PromiseStatus!=='pending') return
self.PromiseStatus='rejected';
self.PromiseValue=err;
}
this.PromiseStatus ='pending' ;
this.PromiseValue =null;
// 对异常进行处理;使用try catch
try{
executor(resolve,reject);
}catch(err){
reject(err);
}
}
// 自定义封装then方法执行回调
Promise.prototype.then=function(onResolve,onReject){
//下面的this是指向实例对象p的哈;
//{PromiseStatus:"resolved"PromiseValue:"ok"}
if(this.PromiseStatus==='resolved'){
onResolve(this.PromiseValue)
}
if(this.PromiseStatus==='rejected'){
onReject(this.PromiseValue)
}
}
遇见问题,这是你成长的机会,如果你能够解决,这就是收获。
作者:晚来南风晚相识
出处:https://www.cnblogs.com/IwishIcould/
本文版权归作者所有,欢迎转载,未经作者同意须保留此段声明,在文章页面明显位置给出原文连接
如果文中有什么错误,欢迎指出。以免更多的人被误导。
出处:https://www.cnblogs.com/IwishIcould/
想问问题,打赏了卑微的博主,求求你备注一下的扣扣或者微信;这样我好联系你;(っ•̀ω•́)っ✎⁾⁾!
如果觉得这篇文章对你有小小的帮助的话,记得在右下角点个“推荐”哦,或者关注博主,在此感谢!
万水千山总是情,打赏5毛买辣条行不行,所以如果你心情还比较高兴,也是可以扫码打赏博主(っ•̀ω•́)っ✎⁾⁾!
想问问题,打赏了卑微的博主,求求你备注一下的扣扣或者微信;这样我好联系你;(っ•̀ω•́)っ✎⁾⁾!

支付宝

微信
如果文中有什么错误,欢迎指出。以免更多的人被误导。