Home > Blockchain >  Response of last axios-request response is null
Response of last axios-request response is null

Time:11-21

I want to get the current weather conditions of a given place. In order to achieve that I used two APIs. The first one is Mapbox, which I used to geocode the place name to geo-coordinates, and the second is the Accuweather API. I also used the Axios module in order to make HTTP requests to the APIs.

To avoid callback hells and multilayers code and to make it easier to read and maintain I made 3 functions:

  1. cityToCoordinates to get the latitude and longitude of the place/city name.
  2. coordinatesToPlaceID to get the place ID of the coordinates using Accuweather
  3. placeIDToCurrentForecast getting the current weather of the place

I made all three functions async since axios requests use Promises.

The problem is in the placeIDToCurrentForecast function, where the response of the callback in the then function after calling coordinatesToPlaceID is always undefined although the request was made successfully and there was a response that I printed.

Here is the script :

const axios = require("axios").default || require("axios");

const cityToCoordinates = async (cityName) => {
    const geoCodeBaseURL = " https://api.mapbox.com/geocoding/v5/mapbox.places/";
    const mapbowAcessToken = "MAPBOX_TOKEN";
    const limit = 1;
    const cityNameUrlEncoded = encodeURIComponent(cityName);

    return await axios
        .get(
            `${geoCodeBaseURL}${cityNameUrlEncoded}.json?access_token=${mapbowAcessToken}&limit=${limit}`
        )
        .then((response) => {
            const responseObject = response.data;

            if (responseObject.features.length === 0) {
                console.log("Sorry no such place exists");
                return;
            } else {
                const location = responseObject.features["0"].center;
                const longitude = location[0];
                const latitude = location[1];

                return {
                    latitude: latitude,
                    longitude: longitude,
                };
            }
        })
        .catch((error) => {
            console.log("An error has occured in city to coordinates");
            // console.log(error);
        });
};

const coordinatesToPlaceID = async (cityName) => {
    const coordinatesToPlaceApiURL = "http://dataservice.accuweather.com/locations/v1/cities/geoposition/search";
    const accuWeatherApiKey = "ACCUWEATHER_API_KEY";

    await cityToCoordinates(cityName).then(async (response) => {
        const query = `${response.latitude},${response.longitude}`;
        const queryUrlEncoded = encodeURIComponent(query);

        return await axios
            .get(
                `${coordinatesToPlaceApiURL}?q=${queryUrlEncoded}&apikey=${accuWeatherApiKey}`
            )
            .then((response) => {
                console.log(response.data.Key);
                return response.data.Key;
            })
            .catch((error) => {
                console.log("An error has occured in coordinates to place ID");
                // console.log(error);
            });
    });
};

const placeIDToCurrentForecast = async (cityName) => {
    const placeIdToCurrentWeather = "http://dataservice.accuweather.com/currentconditions/v1/";
    const accuWeatherApiKey = "ACCUWEATHER_API_KEY";

    await coordinatesToPlaceID(cityName).then(async (response) => {
        console.log(response); // Always undefined!!!

        if (response) {
            const placeId = response;

            await axios
                .get(`${placeIdToCurrentWeather}${placeId}?apikey=${accuWeatherApiKey}`)
                .then((response) => {
                    console.log(
                        "The current weathr in "  
                        cityName  
                        " is "  
                        response.data[0].Temperature.Metric.Value  
                        "° C"
                    );
                })
                .catch((error) => {
                    console.log("An error has occured in place ID to current forecast");
                    // console.log(error);
                });
        } else {
            console.log("There is no response");
        }
    });
};

placeIDToCurrentForecast("California");

The output :

332131
undefined
There is no response

Why is the response undefined, and how can I improve the code?

CodePudding user response:

You are returning undefined in the coordinatesToPlaceID function, check that. In addition, if you are using then you can avoid to use async-await, vice-versa

const coordinatesToPlaceID = (cityName) => {
    const coordinatesToPlaceApiURL = "http://dataservice.accuweather.com/locations/v1/cities/geoposition/search";
    const accuWeatherApiKey = "ACCUWEATHER_API_KEY";

    return cityToCoordinates(cityName).then((response) => {
        const query = `${response.latitude},${response.longitude}`;
        const queryUrlEncoded = encodeURIComponent(query);

        return axios
            .get(
                `${coordinatesToPlaceApiURL}?q=${queryUrlEncoded}&apikey=${accuWeatherApiKey}`
            )
            .then((response) => {
                console.log(response.data.Key);
                return response.data.Key;
            })
            .catch((error) => {
                console.log("An error has occured in coordinates to place ID");
                // console.log(error);
            });
    });
};
  • Related