简体   繁体   中英

value is correct before return statement, but undefined in other parts of the code

I am programming a Discord bot with many functions that call APIs so I added a functions.js file to my project with different functions that I seem to use often such as getting the data back from an API call.

In my functions.js file I have code like this:

const axios = require('axios');

function randomEl(arr) {
    const index = Math.floor(Math.random() * arr.length);
    return arr[index];
}

function axiosGet(url) {
    axios.get(url).then((response) => {
        const { data } = response;
        return data;
    }).catch((err) => {
        throw err;
    });
}

module.exports = {
    randomEl,
    axiosGet
}

I put a console.log before the return statement and it showed the axios data, but when I log the value the function returns in my index.js file it is undefined .

My index.js file looks like this:

const fns = require('./functions.js');

try {
    const url = `https://api.tenor.com/v1/search?q=${searchTerm}&key=${process.env.TENNOR_KEY}`;
    const data = fns.axiosGet(url);
    console.log(data);
} catch (err) {
    console.log(err);
    msg.reply('An Error Has Occured');
}

The data in this portion of code is undefined , but in the actual axiosGet function before the return it shows the correct data when I log it.

There seem to be two issues in your code. First, it looks like you forgot to return the result of axios.get . Try changing your axiosGet function to the following:

function axiosGet(url) {
    return axios.get(url).then((response) => {
        const { data } = response;
        return data;
    }).catch((err) => {
        throw err;
    });
}

Next, since axiosGet returns a Promise , you will need to wait for the promise to be fulfilled before you can use the result. If your second code block is inside an async function, you could do the following:

try {
    const url = `https://api.tenor.com/v1/search?q=${searchTerm}&key=${process.env.TENNOR_KEY}`;
    const data = await fns.axiosGet(url);
    console.log(data);
} catch (err) {
    console.log(err);
    msg.reply('An Error Has Occured');
}

Otherwise, you could update it to use the Promise.then method:

const url = `https://api.tenor.com/v1/search?q=${searchTerm}&key=${process.env.TENNOR_KEY}`;
fns.axiosGet(url).then(data => {
    console.log(data);
}).error(err => {
    console.log(err);
    msg.reply('An Error Has Occured');
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM