Skip to content

Instantly share code, notes, and snippets.

@ricardobeat
Last active October 12, 2015 12:50
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 ricardobeat/75e431f6dbf2adb56cfb to your computer and use it in GitHub Desktop.
Save ricardobeat/75e431f6dbf2adb56cfb to your computer and use it in GitHub Desktop.
function AbortablePromise (fn) {
var abortHandler;
function onAbort (abortFn) {
abortHandler = abortFn;
}
var promise = new Promise(function (resolve, reject) {
fn.call(null, resolve, reject, onAbort);
});
promise.abort = function (reason) {
abortHandler && abortHandler.call(null, reason);
}
return promise;
}
var req = new AbortablePromise(function (resolve, reject, onAbort) {
var xhr = $.get('/stuff', {
success: resolve,
error: reject
});
onAbort(function (reason) {
xhr.abort();
reject(new Error(reason));
});
});
setTimeout(function(){
req.abort('Time is up!');
}, 1000);
function Request (url) {
this.xhr = new XMLHttpRequest();
this.promise = new Promise(function (resolve, reject) {
this.reject = reject
this.xhr.onload = resolve
this.xhr.onerror = reject
this.xhr.open('GET', url)
this.xhr.send()
}.bind(this))
}
Request.prototype.then = function (fn) {
this.promise.then(fn)
return this
}
Request.prototype.abort = function (reason) {
this.xhr.abort()
this.reject(new Error(reason))
}
new Request().then(function(){ console.log('done') }).abort('fudeu');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment