Created
April 27, 2016 10:06
-
-
Save frontenddeveloping/da0e6446db1ce66543dc35127eed7c95 to your computer and use it in GitHub Desktop.
ES2015 Deferred Class
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
const PENDING_STATE = 'pending'; | |
const REJECTED_STATE = 'rejected'; | |
const RESOLVED_STATE = 'resolved'; | |
class Deferred { | |
static PENDING_STATE = PENDING_STATE; | |
static REJECTED_STATE = REJECTED_STATE; | |
static RESOLVED_STATE = RESOLVED_STATE; | |
constructor() { | |
let state = PENDING_STATE; | |
let promise = new Promise((resolve, reject) => { | |
this.resolveWith = (value) => { | |
state = RESOLVED_STATE; | |
resolve(value); | |
return this; | |
} | |
this.rejectWith = (value) => { | |
state = REJECTED_STATE; | |
reject(value); | |
return this; | |
} | |
}); | |
this.then = promise.then.bind(promise); | |
this.catch = promise.catch.bind(promise); | |
this.promise = () => promise; | |
this.state = () => state; | |
} | |
} | |
// Tests | |
let a = new Deferred(); | |
let b = new Deferred(); | |
a.rejectWith(2).then(() => {},console.warn.bind(console)); | |
b.resolveWith(1).then(console.info.bind(console)); | |
console.log(a.state(), b.state()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment