promise的原理
1.先执行在创建promise对象时传入的方法
2.把then里面的方法加入到队列内等待
3.调用resolve方法,检测传入值是promise对象还是一个值。如果是个promise对象,则继续调用then方法push到队列,如果是个值则执行缓存在队列内的then里面的方法把resolve传入的值代入并输出结果
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>promise原理</title>
</head>
<body>
<div id="app"></div>
</body>
<script>
class MyPromise {
constructor(fn) {
this.value = null
this.state = 'pending'
this.resolvedCallbacks = [] //异步任务队列
this.rejectedCallbacks = []
try {
fn(this.resolve, this.reject);
} catch (e) {
this.reject(e);
}
}
resolve=(value)=> {
if (value instanceof MyPromise) {
return value.then(this.resolve, this.reject)
}
//通过setTimeout控制执行顺序
setTimeout(() => {
if (this.state === 'pending') {
this.state = 'resolved'
this.value = value
// 执行then里的方法并传入resolve的值
this.resolvedCallbacks.map(cb => cb(this.value))
}
}, 0)
}
reject=(value)=> {
//通过setTimeout控制执行顺序
setTimeout(() => {
if (this.state === 'rejected') {
this.state = 'rejected'
this.value = value
this.rejectedCallbacks.map(cb => cb(this.value))
}
}, 0)
}
then=(onFulfilled, onRejected)=> {
onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : v => v;
onRejected =
typeof onRejected === 'function'
? onRejected
: r => {
throw r
};
if (this.state === 'pending') {
this.resolvedCallbacks.push(onFulfilled);
this.rejectedCallbacks.push(onRejected);
}
if (this.state === 'resolved') {
onFulfilled(this.value);
}
if (this.state === 'rejected') {
onRejected(this.value);
}
}
}
new MyPromise((resolve, reject) => {
setTimeout(() => {
resolve(1)
}, 1000)
}).then(value => {
console.log(value)
})
</script>
</html>
网友评论