Last active
October 12, 2015 12:50
-
-
Save ricardobeat/75e431f6dbf2adb56cfb to your computer and use it in GitHub Desktop.
This file contains 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
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); |
This file contains 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
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