promise 原理

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
TEST PROMISE
<div>
<h1>promise 原理</h1>
<p>
Promise 是一个构造函数:
<ul>
<li>Promise:接受一个执行函数</li>
<li>执行函数里面两个形参:resolve,reject</li>
<li>
<p>Promise的原型上面有个then方法,这个方法接受两个参数(resolveCallback,rejectCallback)</p>
<p>并且把这个两个方法保存到promise的一个回调数组里面,当执行resolve的时候,根据status执行对应的回调方法</p>
<p>如果需要链式回调,则在then方法里面,返回一个新的promise对象,在回调数组里面保存resolveCallback,rejectCallback,和新的promise对象的resolve,reject方法</p>
<p>然后在resolve方法里面执行回调数组里面的resolve方法</p>
</li>
</ul>
</p>
</div>
</body>
<script>
function MyPromise(fn) {
var _this = this
_this.value = null; // resolve,reject的值
_this.status = 'Pending' // promise 的状态,Pending:初始,Fulfilled:resolve,Rejected:reject

_this.deffers = [] // 回调数组每调用一次then,就万里面push一个{onFullFilled:onFullFilled,onRejected:onRejected}
function resolve(val) {
if (_this.status === 'Pending') {
_this.status = 'Fulfilled'
_this.value = val
_this.deffers.forEach(function (item) {
var res;
var onFullFilled = item.cb
var resolve = item.resolve
onFullFilled && (res = onFullFilled(_this.value))
if (typeof res === 'object' && res.then) {
res.then(resolve)
}else {
resolve && resolve(res)
}
})
}
}
function reject(val) {
}
fn(resolve,reject)

}
MyPromise.prototype.then = function (onFullFilled,onRejected) {
var _this = this
return new MyPromise(function (resolve,reject) {
_this.deffers.push({
cb:onFullFilled,
resolve:resolve
})
})
}

var a = new MyPromise(function (reslove,reject) {
setTimeout(function () {
reslove('success')
reject('fail')
}, 1000);
})
a.then(function (res) {
console.log(res)
return (888)
}).then(function (res) {
console.log(9999)
})
</script>
</html>

猜你喜欢

转载自www.cnblogs.com/liangshuang/p/9121309.html
今日推荐