1. 程式人生 > >手寫一個實現基本功能的promse

手寫一個實現基本功能的promse

`<!DOCTYPE html>

<html> <head> <meta charset="utf-8"> <title></title> </head> <body> <script type="text/javascript"> // 手寫一個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)
		// })
	</script>
</body>