Skip to content

Instantly share code, notes, and snippets.

@hakimelek
Last active January 25, 2017 00:44
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 hakimelek/3a4e25182441732e23d729d29bc741b2 to your computer and use it in GitHub Desktop.
Save hakimelek/3a4e25182441732e23d729d29bc741b2 to your computer and use it in GitHub Desktop.
import SimplePromise from 'CustomPromise';
// consuming a ES6 promise:
function doSomething() {
return new SimplePromise((resolve, reject) => {
let condition = true;
if (condition) return resolve(resolveArgument);
return reject(rejectArgument);
});
}
doSomething.then((resolveArgument) => {
// do something with resolveArgument
console.log(resolveArgument);
}).catch((rejectArgument) => {
if (rejectArgument) throw rejectArgument;
});
export default class SimplePromise {
constructor () {
this.status = 'pending'; // 3 states pending, resolved, rejected
this.result = null; // initially set to null
this.callbacks = [];
}
then(onResolved, onRejected) {
if (this.status === 'resolved')
return this.resolve(onResolved, onRejected);
else
this.callbacks.push({
onResolved: onResolved,
onRejected: onRejected
});
}
resolve(value) {
if (this.status === 'rejected') {
this.onRejected(this.result);
} else {
this.onResolved(this.result);
}
return this;
}
onResolved(result) {
if(this.status === 'resolved') return;
this.status = 'resolved';
release(result);
// optional, handle chaining here, if value is another promise
}
reject(error) {
if(this.status === 'resolved') return;
this.status = 'rejected';
release(error);
}
release(value) {
this.result = value;
this.callbacks.forEach((data) => {
this.release(data.onResolved, data.onRejected);
}, this)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment