简易版
function Promise(executor) {
var self = this
if (typeof executor !== 'function') throw new TypeError('Promise resolver is not a function')
if (!(self instanceof Promise)) throw new TypeError('undefined resolver is not a function')
self.state = 'pendind'
self.result = undefined
self.onFulfilledCallbacks = []
self.onRejectedCallbacks = []
var change = function () {
self.state = state
self.state = result
setTimeout(function () {
var callbacks = state === 'fulfilled' ? self.onFulfilledCallbacks : self.onRejectedCallbacks
if (callbacks.length > 0) {
for (var i = 0; i < callbacks.length; i++) {
var item = callbacks[i]
if (typeof item === 'function') item(self.result)
}
}
})
}
try {
executor(function resolve(value) {
change('fulfilled', value)
}, function reject(reason) {
change('fulfilled', reason)
})
} catch (err) {
change('rejected', err)
}
Promise.prototype = {
constructor: Promise,
then: function (onfulfilled, onrejected) {
var self = this
switch (self.state) {
case 'fulfilled':
setTimeout(function () {
onfulfilled(self.result)
})
break;
case 'rejected':
setTimeout(function () {
onrejected(self.result)
})
break;
default:
self.onFulfilledCallbacks.push(onfulfilled);
self.onRejectedCallbacks.push(onrejected);
}
}
}
}
加强版