
๋
ธ๋ง๋ JS ๊ฐ์์์ weather API๋ฅผ ๋ค๋ฃจ๋ค๊ฐ ๋ฑ์ฅํ fetch์ promise
๋ฆฌ์กํธ์์๋ ์ผ์๋๋ฐ ์๋ฆฌ๋ ๋ชจ๋ฅด๊ณ ์ผ๋ ๊ธฐ์ต์ด
๋๊ธฐ์ฒ๋ผ ์ฒ๋ฆฌ๋๋ ๊ฒ์ด ์๋๋ผ ๋ฏธ๋์ ๋ฐ์ดํฐ ์ฒ๋ฆฌ๊ฐ ์๋ฃ๋ ์์ ์ ๊ฒฐ๊ณผ๋ฅผ ์ ๊ณตํ๊ฒ ๋ค๋ โ์ฝ์(ํ๋ก๋ฏธ์ค)โ๋ฅผ ๋ฐํ
๋น์ฅ ๋ญ๊ฐ ์ผ์ด๋์ง ์๊ณ , ์๊ฐ์ด ์ข ๊ฑธ๋ฆฐ ๋ค์ ์ผ์ด๋๋ ๊ฒ
then()์ ์ด์ด๋ถ์ฌ ์ฝ๋ฐฑํจ์ ์์
์ ์ฒ๋ฆฌ => ์ฝ๋ฐฑ์ง์ฅ ๋ฐฉ์ง resolve์ reject๋ก ๋ฐ์ ์ ์์resolve๋ก ๋ฐ์reject๋ก ๋ฐ์JavaScript ๋ด์ฅ API๋ก ๋น๋๊ธฐ ํต์ ๋คํธ์ํฌ๋ฅผ ๊ฐ๋ฅํ๊ฒ ํ๋ ๊ธฐ์
fetch ํจ์๋ url๋ก ์์ฒญ์ ๋ณด๋ธ ๊ฒฐ๊ณผ๋ก Promise ๊ฐ์ฒด๋ฅผ ๋ฐํ
fetch๋ promise ์ด๊ธฐ ๋๋ฌธ์ ์๋ฒ ์๋ต์ ๋ฐ์์ผ ํ๋ค
reject ํ์ง ์์resolve ๋ฐํfetch๋ ๋น๋๊ธฐ๋ก ๋์ํ๊ธฐ ๋๋ฌธ์ ๊ฒฐ๊ณผ ์ฅ๋ด๋ถ๊ฐ async์ await๊ทธ๋ฌ๋๊น!!!
async๋ผ๊ณ ๋น๋๊ธฐ ํจ์๋ฅผ ์ ์ธํด ๋น๋๊ธฐ ์์
์ await๋ฅผ ๋ถ์ฌ์ฃผ๋ฉดconst API_KEY = '123';
function onGeoOk(position) {
const lon = position.coords.longitude;
const lat = position.coords.latitude;
const url = `https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&appid=${API_KEY}&units=metric`;
fetch(url)
.then((response) => response.json())
.then((data) => {
const weather = document.querySelector('#weather span:first-child');
const city = document.querySelector('#weather span:last-child');
weather.innerText = `${data.weather[0].main} / ${data.main.temp}`;
city.innerText = data.name;
});
}
function onGeoError() {
alert("Can't find you. No weather for you");
}
console.log('Requesting geolocation...');
navigator.geolocation.getCurrentPosition(onGeoOk, onGeoError);
interesting!!
Ref. Promise, Fetch, Async, Await ์ ๋ํด ์์๋ณด์, ํฌ๋ก์ฝ๋ฉ