BarkMulcher
BarkMulcher

Reputation: 11

Combining two JavaScript API requests inside of a function

I am very new to JavaScript and as my current assignment, I am to create a simple weather forecast site using openweathermap.org API. The requirements for my assignment dictate that I must be able to fetch weather data by entering only a city name. However, the openweather API requires that the latitude and longitude be included in the request URL. The Forecast API call URL is: https://api.openweathermap.org/data/2.5/onecall?lat={lat}&lon={lon}&exclude={part}&appid={API key} . For this URL, I think I would write:

let forecastApiUrl = 'http://api.openweathermap.org/data/2.5/onecall?lat=' + lat + '&lon=' + lon + '&exclude=minutely&appid={TopSecretApiKey}';

As luck would have it, openweathermap has a GeoCoding API as well! The API call for GeoCoding is: https://api.openweathermap.org/geo/1.0/direct?q={city name}{state code}{country code}&limit={limit}&appid={API key} . I haven't written the URL variable for this yet.

My question is: How do I go about writing the function such that the contents of the GeoCoding API response will be "read" by the Forecast API call, and output my desired weather forecast? This is only my 2nd API exercise, and the only one I've done requiring this additional step. Any advice much appreciated. Please take into consideration that I am an extreme novice.

Upvotes: 0

Views: 161

Answers (1)

niklasbec
niklasbec

Reputation: 1044

This would be best solved with a promise.

You can just async await your first geocaching API request and once that is done you will send the second request to fetch the weather.

Read this

It will look something like this (PSEUDOCODE):


function fetchGeoData() {
     return new Promise((resolve, reject) => {
     
     //Check if your request was successful, if it was resolve(), else reject()
     })

}

async function fetchWeather() {
    const geoData = await fetchGeoData();

    And now you can just fetch your weather here, the payload would look something like:

   {lat: geoData.lat, long: getData.long}

}

Don't forget to build fallbacks in case any of your requests fail.

Upvotes: 1

Related Questions