Last active
September 26, 2017 15:29
-
-
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)`
This file contains 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
'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