0

I am trying to access the Microsoft Azure Management API, and I have gotten to the point where I can console.log() the data from my axios call.

What I can't figure out how to do, is how do I wrap my axios call in a function, and then retrieve that data later on?

My code is below. Note that I see the returned data from the MS api in my console, just like I'd expect.


// Express setup code, module imports, env variables, etc.
// ...

function getAzureToken() {

    // Set up credentials, auth url and request body, axios config
    // The API authenticates properly, so it is not relevant to include
    // ...

    var data = {};
    axios.post(authEndpoint, config)
        .then(result => {
            console.log(result.data) // Logs the expected data (auth token) in my console
            data = result.data
        })
    
    return data 
}

// Index API endpoint
app.get('/', (req, res) => {

    let token = getAzureToken()

    // Prints out this in my browser: {}
    res.send(token)

})


Can anyone give a noob a helping hand?

PetterB
  • 3
  • 2

1 Answers1

1

You need to return in the .then method to extract the value.

// Express setup code, module imports, env variables, etc.
// ...

async function getAzureToken() {

    // Set up credentials, auth url and request body, axios config
    // The API authenticates properly, so it is relevant to include
    // ...

    return await axios.post(authEndpoint, config)
        .then(result => {
            console.log(result.data) // Logs the expected data (auth token) in my console
            return result.data
        })
}

// Index API endpoint
app.get('/', async (req, res) => {

    let token = await getAzureToken()

    // Prints out this in my browser: {}
    res.send(token)

})
Markido
  • 424
  • 3
  • 8
  • This still does not let me access the data after calling getAzureToken(). Just shows up as empty – PetterB Jul 22 '21 at 13:41
  • 1
    `return axios.post()` returns a Promise, in order to get a data from promise you must use async/await or then() `let token = getAzureToken().then((token) => { res.send(token) })` – Nikita Mazur Jul 22 '21 at 13:43
  • 1
    You are right Nikita - i have edited the code to correctly work asynchronously :-) Try the updated version, @user5860749 – Markido Jul 22 '21 at 13:46
  • Thank you both so much!, it is working now with the updated example :) – PetterB Jul 22 '21 at 13:47
  • 1
    You are welcome! dont forget to mark as correct for the next person who drops in here ;) (i can see your account is new). I appreciate the upvote! Good luck – Markido Jul 22 '21 at 13:48
  • 1
    I will be able to mark it as correct in 2 minutes, will do! – PetterB Jul 22 '21 at 13:49