Skip to content

Instantly share code, notes, and snippets.

View keyvan-m-sadeghi's full-sized avatar
🏠
Working from home

Keyvan M. Sadeghi keyvan-m-sadeghi

🏠
Working from home
View GitHub Profile
const states = {
pending: 'Pending',
resolved: 'Resolved',
rejected: 'Rejected'
};
class Nancy {
constructor(executor) {
const resolve = () => {
this.state = states.resolved;
};
const reject = () => {
this.state = states.rejected;
};
const getCallback = state => value => {
this.value = value;
this.state = state;
};
const resolve = getCallback(states.resolved);
const reject = getCallback(states.rejected);
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,
class Nancy {
...
static resolve(value) {
return new Nancy(resolve => resolve(value));
}
static reject(value) {
return new Nancy((_, reject) => reject(value));
}
}
let p = new Nancy((resolve, reject) => {
resolve(42);
reject(24); // ignored
resolve(); // ignored
});
p
.then(value => Nancy.reject(value)) // rejects
.catch(value => console.log(value)); // logs 42
const delay = milliseconds => new Nancy(resolve => setTimeout(resolve, milliseconds));
const logThenDelay = milliseconds => total => {
console.log(`${total / 1000.0} seconds!`);
return delay(milliseconds)
.then(() => total + milliseconds);
};
logThenDelay(500)(0) // logs 0 seconds!
.then(logThenDelay(500)) // after 0.5 seconds, logs 0.5 seconds!
.then(logThenDelay(500)) // after 1 second, logs 1 seconds!
class Nancy {
constructor(executor) {
const tryCall = callback => Nancy.try(() => callback(this.value));
const members = {
[states.resolved]: {
...
then: trycall
},
...
};
const anything = () => {
throw new Error('I can be anything because I should never get called!');
};
const throwSomethingWrong = () => {
console.log('not ignored!');
throw new Error('Something went wrong...');
};
const p = Nancy.reject(42)
.catch(value => value) // resolves
[states.resolved]: {
...
then: tryCall,
catch: _ => this
},
[states.rejected]: {
...
then: _ => this,
catch: tryCall
}