-
-
Save kriskowal/312929 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
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