Skip to content

Instantly share code, notes, and snippets.

@Elshaman
Created September 18, 2020 21:24
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save Elshaman/c839f499d2bf81930f0713f71977f541 to your computer and use it in GitHub Desktop.
asynchronous api request(Chapter 11): Classic, stone-aged XMLHttpRequest object , in web browser.....Promises..... In arrow Syntax
/**
* Cristian Buitrago´s Weather API
* 9th Iteration
* Sample with Old School´s XMLHttpRequest, in web browser (Arrow Syntax this time)
* Execute: browser
* Architectural style: Promises
* method: GET
* Calls openweathermap's API(openweathermap.com/current for info)
*/
get_weather_data = (url)=>{
return new Promise( (resolve, reject)=>{
let httpRequest = new XMLHttpRequest();
httpRequest.open('GET', url);
httpRequest.onload = () => {
if(httpRequest.status === 200){
resolve(httpRequest.responseText);
}else{
reject(Error(httpRequest.status));
}
}
//gestionar errores de red
httpRequest.onerror = ()=>{
reject(Error("Error de red "));
}
httpRequest.send();
})
}
failHandler = (status)=>{
console.log(status);
}
success = (response) => {
const dataObj = JSON.parse(response);
console.log(dataObj.main.temp)
}
const apiKey = 'your_api_key';
const url = `https://api.openweathermap.org/data/2.5/weather?id=3688685&APPID=${apiKey}`;
get_weather_data(url)
.then((response) => {
success(response)
})
.catch((status) => {
failHandler(status)
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment