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);
})
};
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)
– Carltee
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..
– Marcelo Batista