Skip to content

Instantly share code, notes, and snippets.

@getify
Created February 16, 2010 06:38
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 getify/305353 to your computer and use it in GitHub Desktop.
Save getify/305353 to your computer and use it in GitHub Desktop.
(function(global){
var undef;
function Promise(){}
Promise.prototype.constructor = Promise;
global.promise = function(cb) {
var publicAPI, queue = [], old_ret, promise_fulfilled = false;
function fulfill(val) {
var ret_val = val;
if (typeof ret_val != "undefined") old_ret = ret_val;
try {
return val;
}
finally {
for (var i=0,len=queue.length; i<len; i++) {
if (typeof ret_val != "undefined") old_ret = ret_val;
ret_val = queue[0].call(publicAPI,ret_val);
if (typeof ret_val == "undefined") { ret_val = old_ret; }
else if (ret_val.constructor !== Promise) old_ret = ret_val; // lame, V8 "instanceof" currently broken
queue.shift();
if (ret_val.constructor === Promise) { // lame, V8 "instanceof" currently broken
promise_fulfilled = false;
ret_val.then(function(P){ promise_fulfilled = true; return (old_ret = fulfill(P.value)); });
break;
}
}
}
}
publicAPI = new Promise();
publicAPI.then = function(cb){
queue[queue.length] = function(val){ return cb.call(publicAPI,{value:val}); };
if (promise_fulfilled) fulfill(old_ret);
return publicAPI;
};
cb.call(publicAPI,{fulfill:function(val){
promise_fulfilled = true;
fulfill.call(publicAPI,val);
},value:undef});
return publicAPI;
};
})(window);
var Load = function(src,cb) {
var xhr = new XMLHttpRequest();
xhr.open("GET",src);
xhr.onreadystatechange = function(){
if (xhr.readyState == 4) {
cb(xhr.responseText);
}
};
xhr.send();
};
promise(function(P){
Load("abc.js",P.fulfill);
})
.then(function(P){
return promise(function(P2){
setTimeout(function(){
P2.fulfill(P.value);
},2000);
});
})
.then(function(P){
return P.value.toUpperCase();
})
.then(function(P){
return promise(function(P2) {
setTimeout(function(){
P2.fulfill(P.value);
},1000);
})
.then(function(P){
return P.value+"!";
});
})
.then(function(P){
// do nothing -- silently pass along P.value
})
.then(function(P){
console.log(P.value);
});
promise(function(P){
P.fulfill("Hello");
})
.then(function(P){
return promise(function(P2){
P2.fulfill(P.value+" World");
})
.then(function(P){
return P.value.toUpperCase();
});
})
.then(function(P){
console.log(P.value+"!");
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment