Last active
October 14, 2016 10:57
-
-
Save tphdev/ffca2aa07f10e097479c56b23f461920 to your computer and use it in GitHub Desktop.
simple promise implementation
This file contains hidden or 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
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