Skip to content

Instantly share code, notes, and snippets.

@danielsan
Last active May 21, 2020 19:18
Show Gist options
  • Save danielsan/6adfc8f416eab8fe97d21548b70672d5 to your computer and use it in GitHub Desktop.
Save danielsan/6adfc8f416eab8fe97d21548b70672d5 to your computer and use it in GitHub Desktop.
promise-magic
const sleep = (n, ...args) => new Promise((resolve) => { setTimeout(resolve, n, ...args) })
const sleepError = (n, error) => ({
timeout: null,
prom: null,
clearMyTimeout () {
clearTimeout(this.timeout)
this.prom && this.prom.resolve()
},
get promise () {
this.prom = new Promise((resolve, reject) => {
// potentially avoiding memory leaks
setImmediate(() => { this.prom.resolve = resolve })
this.timeout = setTimeout(reject, n, error)
})
return this.prom
}
})
class PM {
#thePromise = null
constructor () {
this.preparePromise()
}
async waitForThatThingToHappenOrTimesOut (timeout = 15_000 ) {
const sleepingBeauty = sleepError(timeout, new Error('thisHasTimedout'))
return Promise.race([
this.#thePromise,
sleepingBeauty.promise
]).finally(() => {
sleepingBeauty.clearMyTimeout()
})
}
async preparePromise () {
// let innerResolve =
this.#thePromise = new Promise((resolve) => process.nextTick(() => {
this.#thePromise.resolve = resolve
}))
// this.#thePromise = new Promise((resolve) => {
// innerResolve = resolve
// })
// this.#thePromise.resolve = innerResolve
}
resolveFromOutside (v) {
this.#thePromise.resolve(v)
}
}
async function resolveExample () {
const pm = new PM()
pm.waitForThatThingToHappenOrTimesOut()
.then(console.log.bind(0, 'SUCESS'))
.catch(console.error.bind(0, 'Shit Man!'))
await sleep(100)
pm.resolveFromOutside('Nothing')
}
async function rejectExample (timeout = 10_000) {
const pm = new PM()
await pm.waitForThatThingToHappenOrTimesOut(timeout)
.then(console.log.bind(0, 'SUCESS'))
.catch(console.error.bind(0, 'Shit Man!'))
}
module.exports = {
PM,
sleep,
sleepError,
resolveExample,
rejectExample
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment