Last active
January 25, 2017 00:44
-
-
Save hakimelek/3a4e25182441732e23d729d29bc741b2 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
}); | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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