JSFiddle - React, Tailwind, and code Playground
by Alexey
JavaScript
function noop() {}
class VladilenPromise {
constructor(executor) {
this.queue = []
this.errorHandler = noop
this.finallyHandler = noop
try {
executor.call(null, this.onResolve.bind(this), this.onReject.bind(this))
} catch (e) {
this.errorHandler(e)
} finally {
this.finallyHandler()
}
}
onResolve(data) {
console.log('1', data);
this.queue.forEach(callback => {
data = callback(data);
console.log('2', data);
})
this.finallyHandler()
}
onReject(error) {
this.errorHandler(error)
this.finallyHandler()
}
then(fn) {
this.queue.push(fn)
console.log('from then')
return this
}
catch (fn) {
this.errorHandler = fn
return this
} finally(fn) {
this.finallyHandler = fn
return this
}
}
const promise = new VladilenPromise((resolve, reject) => {
setTimeout(() => {
resolve(12345)
//reject('Some Error')
}, 1000)
})
promise
.then(course => course * 3)
.then(title => console.log('Alex Promise:', title))
/* .catch(err => console.log('Error:', err)) */
/* .finally(() => console.log('Finally')) */