Skip to content

Instantly share code, notes, and snippets.

@ghyghoo8
Created August 23, 2021 09:36
Show Gist options
  • Save ghyghoo8/9f642c2bbd383f51cf39189cc389b9e1 to your computer and use it in GitHub Desktop.
Save ghyghoo8/9f642c2bbd383f51cf39189cc389b9e1 to your computer and use it in GitHub Desktop.
promise实现
/**
* Promise 基于发布订阅的设计模式实现,then方法返回一个新的Promise,状态由上一个promise决定。
*/
Promise.prototype.then=function(onResolved,onRejected){
const self= this
return new Promise((resolve,reject)=>{
// 把相同的代码封装起来,并用try catch捕获错误
/*
像这种情况,使用者如果抛出错误,直接让下个promise也就是当前返回的promise状态为失败
then(res=>{
throw '我抛出错误'
})
*/
function handle (callback){
try {
const result= callback(self.state)
if(result instance Promise){
result.then(res=>{
resolve(res)
})
} else {
resolve(result)
}
}catch(reason){
reject(reason)
}
}
// 当前Promise pending状态时
if(seft.status===PENDING){
seft.callbackQueues.push({
onResolved,
onRejected
})
// 当前Promise fulfilled状态时
}else if(seft.status===FULFILLED){
setTimeout(()=>{
handle(onResolved)
})
// 当前Promise 为rejected状态时
else {
setTimeout(()=>{
handle(onRejected)
})
}
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment