Skip to content

Instantly share code, notes, and snippets.

@nerboda
Last active May 2, 2018 21:09
Show Gist options
  • Save nerboda/8c0eacf93a940beca7d0dff38e53663f to your computer and use it in GitHub Desktop.
Save nerboda/8c0eacf93a940beca7d0dff38e53663f to your computer and use it in GitHub Desktop.
Promises
function MyPromise(action) {
this.status = 'pending';
this.value = undefined;
this.thenCallbacks = [];
this.onCatch = undefined;
this.onFinally = undefined;
this.then = function(callback) {
this.thenCallbacks.push(callback);
return this;
};
this.catch = function(callback) {
this.onCatch = callback;
return this;
};
this.finally = function(callback) {
this.onFinally = callback;
return this;
};
// Do the thing
action(resolver.bind(this), rejector.bind(this));
// Private
function resolver(value) {
this.status = 'resolved';
this.value = value;
this.thenCallbacks.forEach(function(func) {
func(this.value);
}, this);
if (typeof this.finallyCallback === 'function') {
this.finallyCallback(this.value);
}
}
function rejector(value) {
this.status = 'rejected';
this.value = value;
if (typeof this.catchCallback === 'function') {
this.catchCallback(this.value);
}
if (typeof this.finallyCallback === 'function') {
this.finallyCallback(this.value);
}
}
}
function get(url) {
return new MyPromise(function(resolve, reject) {
var request = new XMLHttpRequest();
request.open('GET', url);
request.onload = function() {
if (request.status === 200) {
resolve(request.response);
}
else {
reject(Error(request.statusText));
}
};
request.onerror = function() {
reject(Error('Network Error'));
};
request.send();
});
}
get('https://nerboda.github.io')
.then(function(response) {
console.log(response);
})
.catch(function(error) {
console.log(error);
})
.then(function(result) {
console.log(result);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment