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 tryCall = callback => Nancy.try(() => callback(this.value));
const laterCalls = [];
class Nancy {
constructor(executor) {
...
const laterCalls = [];
const callLater = getMember => callback => new Nancy(resolve => laterCalls.push(() => resolve(getMember()(callback))));
const members = {
...
[states.pending]: {
...
then: callLater(() => this.then),
let p = delay(500);
p.then(() => console.log('1st then!')); // after 0.5 seconds, logs 1st then!
p.then(() => console.log('2nd then!')); // after 0.5 seconds, logs 2nd then!
p.then(() => console.log('3rd then!')); // after 0.5 seconds, logs 3rd then!
p = p.then(() => Nancy.reject());
p.catch(() => console.log('1st catch!')); // after 0.5 seconds, logs 1st catch!
p.catch(() => console.log('2nd catch!')); // after 0.5 seconds, logs 2nd catch!
p.catch(() => console.log('3rd catch!')); // after 0.5 seconds, logs 3rd catch!
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!
const apply = (value, state) => {
// Ignore subsequent calls to resolve and reject
if (this.state === states.pending) {
this.value = value;
changeState(state);
}
};
const getCallback = state => value => {
// Unpack on resolve
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 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
}
class Nancy {
constructor(executor) {
const tryCall = callback => Nancy.try(() => callback(this.value));
const members = {
[states.resolved]: {
...
then: trycall
},
...
};
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,