To jest utworzenie i wywołanie funkcji JS (blok z funkcją)(wywołanie) np.:
(() => console.log(123)) // sama definicja
(() => console.log(123))(); // definicja + wywołanie
((a) => console.log(a))(123) // wywołanie z argumentem
Jednak jak na moje oko zupełnie niepotrzebne w powyższym kodzie, tylko komplikuje kod.
IIFE (Immediately Invoked Function Expression) było po, bo nie chciało mi się zmieniać nazw zmiennych. Obie funkcje getWeather
i getAdvice
miały zmienną (właściwie to stałą) data
. Po scaleniu tych dwóch funkcji w jedną, ta zmienna by kolidowała.
Można było to przerobić prościej np. tak
async function getData() {
await Promise.all([
axios.get(`https://api.openweathermap.org/data/2.5/weather?q=${inputCity.value}&appid=${weatherApiKey}&units=metric`),
axios.get("https://api.adviceslip.com/advice")
]).then(([weatherResponse, adviceResponse]) => {
// weather
console.log(weatherResponse.data);
cityFound.value = false;
const {
data: { main, name, weather, sys },
} = weatherResponse;
const ref = weatherData.value;
ref.city = name;
ref.country = sys.country;
ref.temperature = parseInt(main.temp);
ref.temperatureFellsLike = parseInt(main.feels_like);
ref.temperatureMin = main.temp_min;
ref.temperatureMax = main.temp_max;
ref.description = weather[0].description;
ref.iconUrl = `https://openweathermap.org/img/w/${weather[0].icon}.png`;
// advice
adviceForTheDay.value = adviceResponse.data.slip.advice;
}).finally(() => {
inputCity.value = "";
cityFound.value = true;
});
}
Ale szybciej dla mnie było po prostu skopiować obie funkcje i je domknąć. Można też było je zamknąć w osobnych blokach {}
. I przypisać w każdym np. const response = weatherResponse
Chyba zdecyduję się na taką wersję:
async function fetchData() {
const promise1 = await axios.get(
`https://api.openweathermap.org/data/2.5/weather?q=Opole&appid=${weatherApiKey}&units=metric`
);
const promise2 = await axios.get("https://api.adviceslip.com/advice");
Promise.all([promise1, promise2]).then((response) => {
console.log(response[0]);
console.log(response[1].data.slip.advice);
});
}
Coś takiego, to tylko próbka kodu.
Tutaj wywołujesz dwie funkcje sekwencyjnie. Jak już coś to:
async function fetchData() {
const promise1 = axios.get(
`https://api.openweathermap.org/data/2.5/weather?q=Opole&appid=${weatherApiKey}&units=metric`
);
const promise2 = axios.get("https://api.adviceslip.com/advice");
Promise.all([promise1, promise2]).then((response) => {
console.log(response[0]);
console.log(response[1].data.slip.advice);
});
}