Fetch function in JavaScript returns undefined
Hello,
I made a small function called makeRequest, which, receiving a URL as a parameter, makes a simple GET request for the URL using the FETCH method.
I am using a simple GitHub endpoint, where my request is arriving normally, and returning the requested data in JSON format.
However, I put this logic inside the method makeRequest , and upon returning this data from the function, it is coming undefined.
I would like to know what I am doing wrong, follow 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);
})
};
0
1 answers
What's going on in your code and what you're 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">
1
Author: Marcelo Batista, 2020-03-02 12:47:19