<script>
const PENDING="pending";
const FULFILLED = "fulfiled";
const REJECTED = "rejected";
function MyPromise(fn){
let _this=this;
_this.state=PENDING;
_this.value="";
_this.reason="";
_this.fulfilledFnArr=[];
_this.rejectedFnArr=[];
function resolve(value){
_this.state=FULFILLED;
_this.value=value;
_this.fulfilledFnArr.forEach((item)=>{
item();
})
}
function reject(reason){
_this.state=REJECTED;
_this.reason=reason;
_this.rejectedFnArr.forEach((item)=>{
item()
})
}
fn(resolve,reject)
}
MyPromise.prototype.then=function(onFulfilledFn,onRejectedFn){
var _this=this;
// 针对同步方法
if(_this.state==FULFILLED){
console.log("----FULFILLED---")
return new MyPromise(function(resolve,reject){
var x = onFulfilledFn(_this.value);
if(x instanceof MyPromise){
x.then(resolve,reject)
}else{
resolve(x)
}
})
}
if(_this.state==REJECTED){
return new MyPromise(function(resolve,reject){
var x = onRejectedFn(_this.reason);
if(x instanceof MyPromise){
x.then(resolve,reject)
}else{
resolve(x)
}
})
}
// 针对异步方法
if(_this.state==PENDING){
return new MyPromise(function(resolve,reject){
console.log("----PENDING---")
_this.fulfilledFnArr.push(()=>{
var x = onFulfilledFn(_this.value);
if(x instanceof MyPromise){
x.then(resolve,reject)
}else{
resolve(x)
}
});
_this.rejectedFnArr.push(()=>{
var x = onRejectedFn(_this.reason);
if(x instanceof MyPromise){
x.then(resolve,reject)
}else{
resolve(x)
}
})
})
}
}
new MyPromise(function(resolve,reject){
setTimeout(() => {
resolve(333)
}, 5000);
}).then(function(res){
console.log(res)
return new MyPromise(function(resolve,reject){
setTimeout(() => {
resolve(8888)
}, 2000);
})
}).then(function(res){
console.log(res)
})
</script>
手写Promise
原创liuhao951866 博主文章分类:知识加深 ©著作权
©著作权归作者所有:来自51CTO博客作者liuhao951866的原创作品,请联系作者获取转载授权,否则将追究法律责任
上一篇:canvas水印
下一篇:express托管静态文件
提问和评论都可以,用心的回复会被更多人看到
评论
发布评论
相关文章
-
TypeScript 中 Promise 深度解析
本文给出Typescript编程中异步对象Promise应用的各种场景,并归纳使用注意事项。
泛型 TypeScript Promise Javascript 链式编程 -
promise用法总结以及手写promise
Promise.all() 接收一个 Promise 数组,返回一个新的 Promise,当所有的 Promise 都成功时,该 Promise 会成功,返回一
前端 javascript 异步操作 回调函数 数组 -
Promise从入门到手写 | [Promise系列一]
从零开始,带着你入门Promise并亲手实现。本文分为四大部分,包括Promise介绍,Promise特点,Promise使用,和Promise手写~
JavaScript 回调函数 返回结果 异步操作
















