Skip to content

Instantly share code, notes, and snippets.

@getify
Created February 24, 2010 00:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save getify/312928 to your computer and use it in GitHub Desktop.
Save getify/312928 to your computer and use it in GitHub Desktop.
// promise() comes from: http://gist.github.com/311586
// show possible "error" handling
function xhrcall(){
return promise(function(P){
var xhr = new XMLHttpRequest();
xhr.open("GET","/");
xhr.onreadystatechange = function(){
if (xhr.readyState == 4) {
if (xhr.responseText.match(/success/)) P.fulfill(xhr.responseText);
else P.reject(xhr.responseText);
}
});
xhr.send();
});
}
xhrcall()
.then(function(P){
alert("success:"+P.value);
})
.broken(function(P){
alert("failure:"+P.value);
});
// alternate format, a little more "when"ish
function xhrcall(win,fail){
var xhr = new XMLHttpRequest();
xhr.open("GET","/");
xhr.onreadystatechange = function(){
if (xhr.readyState == 4) {
if (xhr.responseText.match(/success/)) win(xhr.responseText);
else fail(xhr.responseText);
}
});
xhr.send();
}
promise(function(P){
xhrcall(P.fulfill,P.fail);
})
.then(function(P){
alert("success:"+P.value);
})
.broken(function(P){
alert("failure:"+P.value);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment