Created
September 18, 2020 21:24
Star
You must be signed in to star a gist
asynchronous api request(Chapter 11): Classic, stone-aged XMLHttpRequest object , in web browser.....Promises..... In arrow Syntax
This file contains 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
/** | |
* 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