Skip to content

Instantly share code, notes, and snippets.

@pmuellr

pmuellr/rpromise.js

Last active Sep 26, 2017
Embed
What would you like to do?
Promise class that returns promises that can be directly resolved or rejected via `.resolve(data)` or `.reject(data)`
'use strict'
// prints "0ms", then "1000ms", then "2000ms", ...
function main () {
for (let i = 0; i < 5; i++) {
const pr = new RPromise()
const millis = i * 1000
setTimeout(() => pr.resolve(`${millis}ms`), millis)
pr.then(data => console.log(data))
}
}
// creates promises with resolve() and reject() methods
class RPromise {
constructor () {
const promise = new Promise((resolve, reject) => {
this.resolve = resolve
this.reject = reject
})
this.then = (fn) => promise.then(fn)
this.catch = (fn) => promise.catch(fn)
}
}
if (require.main === module) main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.