0

I have this simple JS code using fetch:

var foto;
var fotoURL;
var EmployeeID;
fetch("URL", {
    method: 'GET',
    headers: {
        'Accept': 'application/json',
    },
})
.then(response => response.text())
.then(text => { 
    foto = JSON.parse(text)
    fotoURL = foto.PictureUrl
    EmployeeID = foto.UserProfileProperties[110].Value
    console.log('numero' + foto.UserProfileProperties[110].Value);
})

console.log(foto.UserProfileProperties[110].Value);

The last console is giving me undefined. Because it is async.

I have tried to use async and await on the code, but I still can't get the value on my last console that it need to be outside the async function.

    async function getResponse() {
    const response = await fetch(
        'URL',
        {
            method: 'GET',
            headers: {
                'Accept': 'application/json',
            }
        }
    );
    const text = await response.text();
    const foto = await JSON.parse(text);
    console.log('numero' + foto.UserProfileProperties[110].Value);
}
console.log('numero' + foto.UserProfileProperties[110].Value);

What I am doing wrong ? I am tring to understand the async and await, but it is not easy.

Thanks in advance.

CSAnimor
  • 137
  • 7
  • 1
    Unfortunately you can't, `async` by nature is something that's going to happen in the future, that last console you have is getting executing `now`, and not the future. You either add another `then`, or place the code inside the `async` function and use `await`. – Keith Mar 21 '23 at 16:45

0 Answers0