Skip to content

Instantly share code, notes, and snippets.

@kmoskwiak
Last active September 6, 2018 21:38
Show Gist options
  • Save kmoskwiak/4244e4b7834b5c524f9145cb9533e01a to your computer and use it in GitHub Desktop.
Save kmoskwiak/4244e4b7834b5c524f9145cb9533e01a to your computer and use it in GitHub Desktop.
class Promyse {
constructor(userFunction) {
this.state = 'pending';
this.thenCallback = null;
this.errorCallback = null;
userFunction(this._resolve.bind(this), this._reject.bind(this));
}
_resolve(data) {
this.state = 'fulfilled';
this.data = data;
this.thenCallback(data);
}
_reject(data) {
this.state = 'rejected';
this.data = data;
this.errorCallback(data);
}
then(fn) {
if(this.state === 'fulfilled') {
fn(this.data);
return this;
}
this.thenCallback = fn;
return this;
}
catch(fn) {
if(this.state === 'rejected') {
fn(this.data);
return this;
}
this.errorCallback = fn;
return this;
}
}
function createUser(name) {
return new Promyse((resolve, reject) => {
setTimeout(() => {
if(name === 'Adam') {
return reject(new Error('Such greatness cannot be recreated!'));
}
return resolve('User ' + name + ' created');
}, 3000);
});
}
createUser('Kasper')
.then((response) => {
console.log(response);
})
.catch((err) => {
console.error('Error creating Kasper', err);
});
createUser('Adam')
.then((response) => {
console.log(response);
})
.catch((err) => {
console.error('Error creating Adam', err);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment