0

Can someone please explain in simple terms, how to return data from fetch? I can console.log the information with ease, but I cannot for the life of me get the JSON data that fetch is returning into a variable so I can manipulate the data.

function apiCall(path,options){
    fetch(path,options)
    .then(response => response.json())
        .then(data => console.log(data));
    
}



apiCall("http://localhost:3000/getJSON",{});

Works, and logs the JSON as expected.

The docs state that :

"If a handler function returns a value, the promise returned by .then gets resolved with the returned value as its value."

So, I should be able to return a value from the .then handler function and have it resolve to a value, correct? If I attempt to return a value in:

function apiCall(path,options){
    fetch(path,options)
    .then(response => response.json())
        .then((data) => {
            console.log(data)
            return data;
        });
    
}



let foo = apiCall("http://localhost:3000/getJSON",{});

console.log(foo);

This doesnt work, it correctly logs the data inside the .then on the response.json() function, but doesn't return the value to me in a useable way. Am I fundamentally misunderstanding the way that promises are resolved?

  • Yes, you are fundamentally misunderstanding async programming. Your let foo is a promise. To do something with it, you have to handle the then (or just handle the response in your apiCall function. .For example create a method to handle your response and do (foo.then(result => handleResponse(result)). You'll have to wrap your head around async programming (callbacks (the 'old' way), promises (the 'new' way), and probably rxjs/streams (a bit too much for you right now I think)) – R_Ice Feb 28 '21 at 22:28

0 Answers0