Created
June 22, 2025 10:11
-
-
Save jayarjo/9be68f7421a2e6d960bdb4d6b0cae260 to your computer and use it in GitHub Desktop.
brightdata
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Deferred { | |
_resolved = null | |
_rejected = null | |
_cbs = [] | |
_errorCb = null | |
then(cb) { | |
if (!this._resolved) { | |
this._cbs.push(cb) | |
} else { | |
cb(this._resolved) | |
} | |
return this | |
} | |
catch(cb) { | |
this._errorCb = cb | |
} | |
reject(err) { | |
if (!this._rejected) { | |
this._rejected = err | |
if (typeof this._errorCb === 'function') { | |
this._errorCb(err) | |
} | |
} | |
} | |
resolve(res) { | |
if (this._rejected) { | |
return | |
} | |
if (!this._resolved) { | |
if (this._cbs.length) { | |
let cb = this._cbs.shift() | |
let nextRes = res | |
try { | |
nextRes = cb(nextRes) | |
} catch (err) { | |
this.reject(err) | |
return | |
} | |
if (nextRes instanceof Deferred) { | |
nextRes.then(realNextRes => { | |
this.resolve(realNextRes) | |
}) | |
} else { | |
this.resolve(nextRes) | |
} | |
} else { | |
this._resolved = res | |
} | |
} | |
} | |
} | |
const d = new Deferred() | |
d.then(res => { | |
console.info('1, ', res) | |
return 'a' | |
}) | |
d.then(res => { | |
let d1 = new Deferred() | |
d1.then(res => { | |
console.info('2, ', res) | |
return 'c' | |
}) | |
setTimeout(() => { | |
d1.resolve('b') | |
}, 2000) | |
return d1 | |
}) | |
d.then(res => { | |
throw new Error('Surprise!') | |
}) | |
d.catch(err => { | |
console.info(`Error: ${err.message}`) | |
}) | |
d.resolve('hello') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment