自定义Promise
1.定义整体结构
(function (window) {
function Promise(excutor) {
}
Promise.prototype.then = function (onResolved, onReject) {
}
Promise.prototype.catch = function (onReject) {
}
Promise.resolve = function (value) {
}
Promise.reject = function (reason) {
}
Promise.all = function (promises) {
}
Promise.race = function (promises) {
}
window.Promise = Promise
})(window)
2.then()/catch()的实现
Promise.prototype.then = function (onResolved, onRejected) {
const _this = this
onResolved = typeof onResolved === 'function' ? onResolved : value => value
onRejected = typeof onRejected === 'function' ? onRejected : reason => { throw reason }
return new Promise((resolve, reject) => {
function handle(callback) {
try {
const x = callback(_this.data)
if (x instanceof Promise) {
x.then(resolve, reject)
} else {
resolve(x)
}
} catch (error) {
reject(error)
}
}
if (_this.status === 'resolved') {
setTimeout(() => {
handle(onResolved)
});
} else if (_this.status === 'rejected') {
setTimeout(() => {
handle(onRejected)
});
} else {
_this.callbacks.push({
onResolved(value) {
handle(onResolved)
},
onRejected(reason) {
handle(onRejected)
}
})
}
})
}
Promise.prototype.catch = function (onRejected) {
return this.then(undefined, onRejected)
}
3.all/race()的实现
Promise.all = function (promises) {
const values = new Array(Promise.length)
let resolvedCount = 0
return new Promise((resolve, reject) => {
promises.forEach((p, index) => {
p.then(
value => {
resolvedCount++
values[index] = value
if (resolvedCount === promises.length) {
resolve(values)
}
},
reason => {
reject(reason)
}
)
})
})
}
Promise.race = function (promises) {
return new Promise((resolve, reject) => {
for (var i = 0; i < promises.length; i++) {
Promise.resolve(promises[i]).then(
(value) => {
resolve(value)
},
(reason) => {
reject(reason)
}
)
}
})
}