I'm trying to implement Promise Class with JavaScript (currently only with resolve, no reject).
For some reason, when I use it without setTimeout around the resolve function, I get double console.logs from the 'then' methods , and otherwise it works fine.
That's my code
const STATUSES = {
PENDING: 'PENDING',
RESOLVED: 'RESOLVED',
REJECTED: 'REJECTED',
}
class CustomPromise {
#value = null
#status = STATUSES.PENDING
#thenCallbacks = []
constructor(cb) {
cb(this.#resolve)
}
#updateState = (status, value) => {
this.#status = status
this.#value = value
}
#resolve = (value) => {
this.#updateState(STATUSES.RESOLVED, value)
this.#thenCallbacks.reduce((acc, callback) => callback(acc), this.#value)
}
then = (cb) => {
this.#thenCallbacks.push(cb)
if (this.#status === STATUSES.RESOLVED) {
this.#thenCallbacks.reduce((acc, callback) => callback(acc), this.#value)
}
return this
}
}
new CustomPromise((resolve) => {
resolve(1)
})
.then((value) => {
console.log('first value', value)
return 2
})
.then((value) => {
console.log('second value', value)
return null
})
the result:
Wrapping the 'resolve' like so makes the code run as expected:
setTimeout(() => {
resolve(1)
}, [1000])
thanks!
