Skip to content

Instantly share code, notes, and snippets.

@pmuellr
Last active September 26, 2017 15:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pmuellr/f8b769f568dc1848affce7587a67c640 to your computer and use it in GitHub Desktop.
Save pmuellr/f8b769f568dc1848affce7587a67c640 to your computer and use it in GitHub Desktop.
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