Created
March 21, 2017 13:27
-
-
Save h3xxx/fb3a1d9b97c80207a21bf927f71f1feb to your computer and use it in GitHub Desktop.
Ajax-Promise solution
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
// taken from https://medium.com/front-end-hacking/ajax-async-callback-promise-e98f8074ebd7#.55p53btpl | |
function makeAjaxCall(url, methodType){ | |
var promiseObj = new Promise(function(resolve, reject){ | |
var xhr = new XMLHttpRequest(); | |
xhr.open(methodType, url, true); | |
xhr.send(); | |
xhr.onreadystatechange = function(){ | |
if (xhr.readyState === 4){ | |
if (xhr.status === 200){ | |
console.log("xhr done successfully"); | |
var resp = xhr.responseText; | |
var respJson = JSON.parse(resp); | |
resolve(respJson); | |
} else { | |
reject(xhr.status); | |
console.log("xhr failed"); | |
} | |
} else { | |
console.log("xhr processing going on"); | |
} | |
} | |
console.log("request sent succesfully"); | |
}); | |
return promiseObj; | |
} | |
document.getElementById("userDetails").addEventListener("click", function(){ | |
// git hub url to get btford details | |
var userId = document.getElementById("userId").value; | |
var URL = "https://api.github.com/users/"+userId; | |
makeAjaxCall(URL, "GET").then(processUserDetailsResponse, errorHandler); | |
}); | |
document.getElementById("repoList").addEventListener("click", function(){ | |
// git hub url to get btford details | |
var userId = document.getElementById("userId").value; | |
var URL = "https://api.github.com/users/"+userId+"/repos"; | |
makeAjaxCall(URL, "GET").then(processRepoListResponse, errorHandler); | |
}); | |
function processUserDetailsResponse(userData){ | |
console.log("render user details", userData); | |
} | |
function processRepoListResponse(repoList){ | |
console.log("render repo list", repoList); | |
} | |
function errorHandler(statusCode){ | |
console.log("failed with status", status); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment