How to return the data obtained from a Request outside the scope of the function?

Asked

Viewed 97 times

1

I am creating a javascript code to query the temperature:

const tempo = () => {
    const axios = require("axios");
    const TOKEN = "#myToken";  

    axios.get(`http://apiadvisor.climatempo.com.br/api/v1/locale/city?name=Joinville&state=SC&token=${TOKEN}`).then((response) => {
        const id = response.data[0]["id"];
        axios.get(`http://apiadvisor.climatempo.com.br/api/v1/forecast/locale/${id}/days/15?token=${TOKEN}`).then((response => {
            const local = response.data;
            const dados = {
                cidade: local.name,
                estado: local.state,
                data: local.data[0].date_br,
                probChuva: local.data[0].rain.probability,
                temperatura: {
                    descricao: local.data[0].text_icon.text.phrase.reduced,
                    max: local.data[0].temperature.max,
                    min: local.data[0].temperature.min
                }
            }
        }));
    });
}

I wonder how do I return the object "data" out of the scope of the function time.

1 answer

0


You can make use of Promises since your method is asynchronous. I leave below an example of how it could be done.

The way you’re working:

const tempo = () => {
    return new Promise((resolve, reject) => {
        const axios = require("axios");
        const TOKEN = "#myToken";  

        axios.get(`http://apiadvisor.climatempo.com.br/api/v1/locale/city?name=Joinville&state=SC&token=${TOKEN}`).then((response) => {
            const id = response.data[0]["id"];
            axios.get(`http://apiadvisor.climatempo.com.br/api/v1/forecast/locale/${id}/days/15?token=${TOKEN}`).then((response => {
                const local = response.data;
                const dados = {
                    cidade: local.name,
                    estado: local.state,
                    data: local.data[0].date_br,
                    probChuva: local.data[0].rain.probability,
                    temperatura: {
                        descricao: local.data[0].text_icon.text.phrase.reduced,
                        max: local.data[0].temperature.max,
                        min: local.data[0].temperature.min
                    }
                }

                resolve(dados);
            })).catch(err => reject(err));
        }).catch(err => reject(err));;
    });
}

tempo().then((res) => {
    console.log(res);
});

As a tip I leave to you the use of async/await that is very useful and helps to leave your code clean. I leave below an example of how it could be done:

const tempo = async () => {
    const axios = require("axios");
    const TOKEN = "#myToken";  

    const response = await axios.get(`http://apiadvisor.climatempo.com.br/api/v1/locale/city?name=Joinville&state=SC&token=${TOKEN}`);
    const id = response.data[0]["id"];
    const result = await axios.get(`http://apiadvisor.climatempo.com.br/api/v1/forecast/locale/${id}/days/15?token=${TOKEN}`);
    const local = result.data;
    const dados = {
        cidade: local.name,
        estado: local.state,
        data: local.data[0].date_br,
        probChuva: local.data[0].rain.probability,
        temperatura: {
            descricao: local.data[0].text_icon.text.phrase.reduced,
            max: local.data[0].temperature.max,
            min: local.data[0].temperature.min
        }
    }
    return dados;
}

tempo().then((res) => {
    console.log(res);
});
  • Thank you for giving me this help! It helped me to see that there is so much I can learn.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.