0

I have the function below that sends a fetch request and return a JSON result, I have checked the response and it does return a value that I need, return userid does return me a value, the problem is when I call this function it returns an undefined value even though I have checked it does return a value with the function.

I am looking for a simple solution.

function currentloginid() {
    fetch('http://localhost/gaq/api/api.php?action=userid', {
       method: 'GET',
    }
)
    .then(function(response) {
        response.json().then(function(data) {
            var userid = JSON.parse(data);
            console.log(userid);
            return userid;
        })
    })
}
Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95

1 Answers1

0

You need to return the response.json() output as well. Adding this return should allow you to get the value. If you want to avoid using it in the .then function, you should look into async/await

function currentloginid() {
    return fetch('http://localhost/gaq/api/api.php?action=userid', {
       method: 'GET',
    })
    .then(function(response) {
        return response.json()
    })
    .then(function(data) {
        var userid = data;
        console.log(userid);
        return userid;
    })
    .catch(err){
        //Do some error handling
    }
}

currentloginid().then(function(id) {
  //Do something with it
})
Simen Fjellstad
  • 392
  • 1
  • 17
  • Thanks for the example, what exactly does currentloginid().then(function(id) {}), do? –  Oct 01 '20 at 23:33
  • @Tu-AiLe When you're calling external sources, they do not respond right away, so instead of returning the value itself from the function, we return a "Promise" that the value will come. What we do when calling .then is to provide a callback for when the value comes. Essentially we say "get current login id and when it arrives THEN do something in the function provided" – Simen Fjellstad Oct 03 '20 at 05:49