Skip to content

Instantly share code, notes, and snippets.

@tphdev
Last active October 14, 2016 10:57
Show Gist options
  • Save tphdev/ffca2aa07f10e097479c56b23f461920 to your computer and use it in GitHub Desktop.
Save tphdev/ffca2aa07f10e097479c56b23f461920 to your computer and use it in GitHub Desktop.
simple promise implementation
console.log('wired up!')
var Promiser = {
callBackList: [],
fetchJSON: function(url){
var resolvePromise = function (context) {
var dataResponse = JSON.parse(this.responseText)
var cb = context.callBackList.shift()
setTimeout(cb.bind(context, dataResponse), 0)
}
var oReq = new XMLHttpRequest();
oReq.addEventListener("load", resolvePromise.bind(oReq, this));
oReq.open("GET", url);
oReq.send();
return this
},
whenReady: function(cb){
this.callBackList.push(cb)
return this
}
}
var logAndFetchDetails = function(d){
console.log("Round Uno",d);
Promiser.fetchJSON("http://www.omdbapi.com/?i=" + d.Search[0].imdbID)
}
var logSecondResponse = function(d){
console.log("Sweeet!",d);
}
Promiser.fetchJSON("http://www.omdbapi.com/?s=fight")
.whenReady(logAndFetchDetails)
.whenReady(logSecondResponse)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment