-
-
Save celmaun/dfbeec42010df9208c2ee6c2a4aefa52 to your computer and use it in GitHub Desktop.
Deferred promise
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 DeferredPromise extends Promise { | |
constructor(def = (res, rej)=>{}) { | |
let res, rej; | |
super((resolve, reject)=>{ | |
def(resolve, reject); | |
res = resolve; | |
rej = reject; | |
}); | |
this.resolve = res; | |
this.reject = rej; | |
this.isCancelled = false; | |
} | |
cancel(err) { | |
this.isCancelled = true; | |
this.reject(err || new Error("Cancelled deferred promise.")); | |
} | |
defer(task) { | |
this.task = task; | |
} | |
async execute(...args) { | |
if (!this.task) { | |
return this.reject(new Error("No task defined in deferred promise.")); | |
} | |
try { | |
args.push(this); | |
const value = await this.task.call(this, ...args); | |
this.resolve(value); | |
} catch(err) { | |
this.reject(err); | |
} | |
} | |
} | |
module.exports = DeferredPromise; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment