Skip to content

Commit

Permalink
fix: promise callback tick run
Browse files Browse the repository at this point in the history
  • Loading branch information
cottom committed Mar 4, 2018
1 parent 7dc48c3 commit 9a527d5
Showing 1 changed file with 13 additions and 18 deletions.
31 changes: 13 additions & 18 deletions promise.js
Original file line number Diff line number Diff line change
Expand Up @@ -102,44 +102,39 @@ Promise.prototype._reject = function (val) {
if (this.state !== states.PENDING) return
this.state = states.REJECTED
this.value = val
// console.log('call reject')
this._run()
}

Promise.prototype._handle = function (defer) {
if (this.state === states.PENDING) {
this._defers.push(defer)
} else {
const context = this
const { onFulfilled, onRejected, resolve, reject, onFinal } = defer
const isFulfilled = this.state === states.FULFILLED
const callback = isFulfilled ? onFulfilled : onRejected
if (!callback) {
// first new
onFinal && onFinal();
(isFulfilled ? resolve : reject)(this.value)
setTimeout(function() {
(isFulfilled ? resolve : reject)(context.value)
})
return
}
try {
resolve(callback(this.value))
} catch(e) {
reject(e)
}
setTimeout(function() {
try {
resolve(callback(context.value))
} catch (e) {
reject(e)
}
})

}
}

Promise.prototype._run = function () {
// in the real word, would use micro task not task
setTimeout(() => {
this._defers.forEach((defer) => this._handle(defer))
})
this._defers.forEach((defer) => this._handle(defer))
}

export default Promise

// Promise.all([
// 1,
// Promise.resolve(2),
// new Promise((resolve, reject) => setTimeout(() => resolve(3), 1000))
// ]).then(res => {
// console.log(res)
// }).catch(e => console.log(e))

0 comments on commit 9a527d5

Please sign in to comment.