Skip to content

Instantly share code, notes, and snippets.

@kriskowal
Forked from getify/format-1.js
Created February 24, 2010 00:54
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 kriskowal/312929 to your computer and use it in GitHub Desktop.
Save kriskowal/312929 to your computer and use it in GitHub Desktop.
var Q = require("promise"); // http://gist.github.com/312929
function xhrcall() {
var deferred = Q.Deferred();
return promise(function(P){
var xhr = new XMLHttpRequest();
xhr.open("GET","/");
xhr.onreadystatechange = function(){
if (xhr.readyState == 4) {
if (xhr.responseText.match(/success/))
deferred.resolve(xhr.responseText);
else
deferred.resolve(Q.Rejection(xhr.responseText));
}
});
xhr.send();
});
return deferred.promise;
}
Q.when(xhrcall(), function (content) {
alert('success: ' + content);
}, function (error) {
alert('failure: ' + error);
});
// but the error can propagate backward:
var promise = Q.when(xhrcall(), function (content) {
alert('success: ' + content);
});
Q.when(promise, function () {
// undefined
}, function (error) {
alert('failure: ' + error);
});
// or the error can be resolved:
var promise = Q.when(xhrcall(), function (content) {
alert('success: ' + content);
}, function (error) {
var deferred = Q.Deferred();
setTimeout(function () {
// yeah, you can resolve with an eventual value too:
deferred.resolve(xhrcall());
}, 1000);
return deferred.promise;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment