0

So when we give this function getApiData something to fetch, we want it to actually return the fetched data. At the moment it returns "undefined" and we don't understand why.

    console.log(name)
    if (`${restVar}` != `GET`) {
        bodyData = JSON.stringify(bodyData);
    }
    fetch(`${url}`, {
        method: `${restVar}`,
        headers: {
            'Content-Type': 'application/json'
        },
        body: bodyData
    })
        .then(response => response.json())
        .then(data => {
            console.log('Success:', data);
            return data;
        })
        .catch((error) => {
            console.error('Error:', error)
        });
}```

Any help would be much appreciated :)
  • 1
    Duplicate of [How to return the response from an asynchronous call](https://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call) – Samathingamajig May 02 '22 at 13:58
  • What do you mean? `console.log('Success:', data);` shows 'undefined'? – Onki Hara May 02 '22 at 14:11
  • 1
    @OnkiHara console.log('Success:', data); doesn't show undefined, but "return data" returns undefined. We want it to return data. – DeusExMachina1337 May 02 '22 at 14:20
  • Then you should check out the link provided by @Samathingamajig. You're accessing probably the return value before the async-call is finished. The `return data` in the then-branch returns into nowhere. You should process the data there. – Onki Hara May 02 '22 at 14:30
  • It doesn't "return[] into nowhere", it `resolve`s a Promise. If you `return fetch(...);`, you will return that Promise and you can get the value with `await` or `.then` – Samathingamajig May 02 '22 at 14:36
  • @Samathingamajig: Sure, the fetch() returns a promise, that is resolved in the .then-branch. But where does the data from `return data` go? – Onki Hara May 02 '22 at 14:41
  • @OnkiHara Every `.then` returns a new Promise. See the [MDN reference](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then) – Samathingamajig May 02 '22 at 14:47
  • But IMHO you can only access the returned data by adding another resolver, which was not done. So it ended into nowhere. – Onki Hara May 02 '22 at 15:06

0 Answers0