Johnty
Johnty

Reputation: 264

Result returning undefined in end result but returns result in axios request

var result = [];
const axios = require("axios");
let XBL = 'LINKREADACTED';

function Status() {
    axios.get(XBL).then(res => {
        result.push({
            core: res.data.CoreServices[0],
            payment: res.data.CoreServices[1],
            media: res.data.CoreServices[2],
            gaming: res.data.CoreServices[3]
        });
        console.log(result)
    });
    console.log(result)
    //return result;
}

anyone understand how inside the axios it returns the result I need but just outside it, it returns undefined?

Upvotes: 2

Views: 365

Answers (1)

jasonandmonte
jasonandmonte

Reputation: 2028

It's a timing issue related to asynchronous calls. The outer result call happens before the result inside the .then method. You could refactor the code block so the operations happen inside the .then callback. Or I would recommend flattening out the code block rather than nesting logic inside a callback using async/await.

async function Status() {
    const { data } = await axios.get(XBL);
    // Happens after receiving response data
    result.push({
         core: data.CoreServices[0],
         payment: data.CoreServices[1],
         media: data.CoreServices[2],
         gaming: data.CoreServices[3]
    });
    console.log(result)
    return result;
}

Note that since the Status() function is now async, it will return a promise that resolves the result (See the "Return Value" section on the MDN page of async-await).

So, wherever you call the Status() function, you should either await its result or use then(), as is the case with all promises.

Upvotes: 1

Related Questions