Skip to content

Instantly share code, notes, and snippets.

@frontenddeveloping
Created April 27, 2016 10:06
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 frontenddeveloping/da0e6446db1ce66543dc35127eed7c95 to your computer and use it in GitHub Desktop.
Save frontenddeveloping/da0e6446db1ce66543dc35127eed7c95 to your computer and use it in GitHub Desktop.
ES2015 Deferred Class
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