手写一个实现基本功能的promse

`

		// 手写一个promise
		class Promise2 {
			static stat = 'pending';  // pending|filled|rejected 有三种状态
			static onResolvedCallbacks = []; // 成功之后遍历then中成功的所有回调函数
			static onRejectedCallbacks = [];// 存储then中失败的回调函数
			constructor(fun = ()=>{}) {
			    fun(Promise2.resolve,Promise2.reject)
			}
			static resolve(conent){  // 成功的回调
				Promise2.stat = 'filled';
				// 成功之后遍历then中失败的所有回调函数
				Promise2.onResolvedCallbacks.reduce((now,next)=>{
					return next(now)
				},conent)
			}
			static reject(conent){  // 失败 回调
				Promise2.stat = 'rejected';
				// 失败之后遍历then中失败的所有回调函数
				Promise2.onRejectedCallbacks.reduce((now,next)=>{
					return next(now)
				},conent);
			}
			then(fun = ()=>{}){  // 正常回调
				Promise2.onResolvedCallbacks.push(fun);
				return this;
			}
			catch(fun = ()=>{}){  // 错误捕获方法
				Promise2.onRejectedCallbacks.push(fun);
				return this;
			}
			finally(fun = ()=>{}){
				Promise2.onResolvedCallbacks.push(fun);
				Promise2.onRejectedCallbacks.push(fun);
			}
		}
		
		let callPromise2 = new Promise2((resolve,reject)=>{
			setTimeout(()=>{
				const num = 111;
				reject(num)
			},2000)
		})
		
		callPromise2.then((res)=>{
			console.log(res)
			return 222
		}).then((res)=>{
			console.log(res)
			return 333
		}).catch((error)=>{
			console.log(error)
		}).finally((end)=>{
			console.log(end)
		})
		
		// Promise.resolve(111).then((res)=>{
		// 	console.log(res)
		// })
		// Promise2.resolve(111).then((res)=>{
		// 	console.log(res)
		// })

转载于:https://my.oschina.net/u/3971746/blog/3086075

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值