Skip to content

Instantly share code, notes, and snippets.

@keyvan-m-sadeghi
Last active February 14, 2019 21:09
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 keyvan-m-sadeghi/554a548978c3ec3fad61d1858b4d6fd0 to your computer and use it in GitHub Desktop.
Save keyvan-m-sadeghi/554a548978c3ec3fad61d1858b4d6fd0 to your computer and use it in GitHub Desktop.
class Nancy {
constructor(executor) {
const members = {
[states.resolved]: {
state: states.resolved,
// Chain mechanism
then: onResolved => Nancy.resolve(onResolved(this.value))
},
[states.rejected]: {
state: states.rejected,
// Ignore mechanism
then: _ => this
},
[states.pending]: {
state: states.pending
}
};
const changeState = state => Object.assign(this, members[state]);
const getCallback = state => value => {
this.value = value;
changeState(state);
};
const resolve = getCallback(states.resolved);
const reject = getCallback(states.rejected);
changeState(states.pending);
try {
executor(resolve, reject);
} catch (error) {
reject(error);
}
}
static resolve(value) {
return new Nancy(resolve => resolve(value));
}
static reject(value) {
return new Nancy((_, reject) => reject(value));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment