es6 promise原理是什么?
es6 promise实现可以简单写一写么?55
// 三个常量⽤于表示状态
const PENDING = 'pending'
const RESOLVED = 'resolved'
const REJECTED = 'rejected'
function MyPromise(fn) {
const that = this
this.state = PENDING
// value 变量⽤于保存 resolve 或者 reject 中传⼊的值
this.value = null
// ⽤于保存 then 中的回调,因为当执⾏完 Promise 时状态可能还是等待中,这时候应该把
that.resolvedCallbacks = []
that.rejectedCallbacks = []
function resolve(value) {
// ⾸先两个函数都得判断当前状态是否为等待中
if(that.state === PENDING) {
that.state = RESOLVED
that.value = value
// 遍历回调数组并执⾏
that.resolvedCallbacks.map(cb=>cb(that.value))
}
}
function reject(value) {
if(that.state === PENDING) {
that.state = REJECTED
that.value = value
that.rejectedCallbacks.map(cb=>cb(that.value))
}
}
// 完成以上两个函数以后,我们就该实现如何执⾏ Promise 中传⼊的函数了
try {
fn(resolve,reject)
}cach(e){
reject(e)
}
}
// 最后我们来实现较为复杂的 then 函数
MyPromise.prototype.then = function(onFulfilled,onRejected){
const that = this
// 判断两个参数是否为函数类型,因为这两个参数是可选参数
onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : v=>v
onRejected = typeof onRejected === 'function' ? onRejected : e=>throw e
// 当状态不是等待态时,就去执⾏相对应的函数。如果状态是等待态的话,就往回调函数中 push
if(this.state === PENDING) {
this.resolvedCallbacks.push(onFulfilled)
this.rejectedCallbacks.push(onRejected)
}
if(this.state === RESOLVED) {
onFulfilled(that.value)
}
if(this.state === REJECTED) {
onRejected(that.value)
}
}
你可以参考如下链接:
https://www.cnblogs.com/minigrasshopper/p/9141307.html
https://blog.csdn.net/grapelove01/article/details/80506327
如果对你有帮助,可以给我个采纳吗,谢谢!! 点击我这个回答右上方的【采纳】按钮
es6 简单实现讲解一下?
<script type="text/javascript">
function P(fn){
this.f = null;
this.ferror = null;
this.then = (f)=>{
this.f = f;
fn(this.a,this.b);
return this;
};
this.error = (f)=>{
this.ferror = f;
fn(this.a,this.b);
return this;
}
this.a = (data)=>{
if(this.f!=null){
this.f(data);
this.f =null;
}
};
this.b = (error)=>{
if(this.ferror!=null){
this.ferror(error);
this.ferror = null;
}
};
}
let p = new P(function(a,b){
//假如成功执行的方法
setTimeout(()=>a("成功了"),1000);
//假如失败执行的方法
//setTimeout(()=>b("失败了"),1000);
})
p.then(function(data){
console.log(data);
}).error(function(error){
console.log(error);
})
</script>
//好像有点不一样。调用then和error会执行两次不行,