Fetch function in Javascript returns Undefined

Asked

Viewed 782 times

0

Hello,

I did a little function called makeRequest, which, by receiving a URL as a parameter, makes a simple GET request to the URL using the FETCH method.

I’m using a simple github endpoint, where my request is coming in normally, and returning the requested data in JSON format.

However, I put this logic within the method makeRequest, and when returning this function data, it is coming Undefined.

I wonder what I’m doing wrong, follows below the code:

var url = "https://api.github.com/users/random-user";

var infoAPI = makeRequest(url);
console.log(infoAPI); //retorna undefined

function makeRequest(url) {
    fetch(url)             
        .then(
            function(response) {
                if (response.status == 404) {                    
                    console.log("User not found, code "+response.status);                    
                    return;
                }                                
                response.json().then(function(data){                    
                    console.log(data); //exibe as informações do usuário
                    return data;                                                            
                });
            }
        )
        .catch(function(error){
            console.log(error);
        })            
};

1 answer

1

What is happening in your code and what you are logging in before you even have the Promise result.

var url = "https://api.github.com/users/random-user";

function makeRequest(url) {
  fetch(url)
    .then(
      function (response) {
        if (response.status == 404) {
          console.log("User not found, code " + response.status);
          return;
        }
        response.json().then(function (data) {
          console.log(data); //exibe as informações do usuário
          return data;
        });
      }
    )
    .catch(function (error) {
      console.log(error);
    })
};


var infoAPI = makeRequest(url);
console.log(infoAPI); //retorna undefined
<!-- begin snippet: js hide: false console: true babel: false -->

    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">

  • I think I get it, this is happening because the function is asynchronous, right? So before the function returns any result, what is assigned in the infoAPI variable is already displayed in the console. Would there be any way where it would be possible to assign this data within a variable? Because my idea was to make a method only to perform the fetchs, and call it several times by passing other endpoints (URL)

  • Its function is already generic, so if you are using the es6 syntax you can export using reserve words like export or export default and pass the parameter and resolve to Promise for example: const obtainResult = async () => { var result = await makeRequest(url); console.log(result) }; or with makeRequest(url). then, etc..

Browser other questions tagged

You are not signed in. Login or sign up in order to post.