0

I have a fetch function inside a async function. I would like to be able to call my data variable outside the async() function. I can do that when using only fetch function but it continues to the next lines of code without waiting to finish fetching data. This question How to return the response from an asynchronous call doesn't solve my problem. It's using ajax. I am expecting having the response outside the function vs inside.

const request = async () => {
  current_url = window.location.href
  network_id = parseInt(current_url.split('/')[5]) 
  const response = await fetch(`http://127.0.0.1:8000/network/${network_id}/edges.geojson/`);
  const data = await response.json();
 }

Any help is appreciated

aba2s
  • 452
  • 2
  • 18
  • `return await response.json()`? – Felix Kling Sep 08 '21 at 09:25
  • @FelixKling, I don't understand. Ialready have await response inside the function – aba2s Sep 08 '21 at 09:31
  • 2
    If you want to get the data "out" of the function you have to return it from that function. – Felix Kling Sep 08 '21 at 09:33
  • 1
    `return response.json()` will work as well. To get the value: `request().then(data => { ... })` or await it: `const data = await request()` – Yousaf Sep 08 '21 at 09:35
  • with var data = await response.json(); I tried return data but when I console.log(data) outside the function I got an error data is undefined – aba2s Sep 08 '21 at 09:37
  • 1
    @aba2s You can't access data like that - `data` is only available inside the function. However, if you return `data` from the function, you can get its value using any of the options shown in the one of the [earlier comment](https://stackoverflow.com/questions/69100385/javascript-get-data-available-outside-an-async-function#comment122128370_69100385) – Yousaf Sep 08 '21 at 09:38
  • @Yousaf, the first method is working fine but the second (const data = await request()) is throwing an error `Uncaught SyntaxError: await is only valid in async functions and the top level bodies of modules`. Lots of thanks ! – aba2s Sep 08 '21 at 09:53
  • @aba2s error message is pretty descriptive - `const data = await reques()` needs to be inside an `async` function. If you don't want to do that, just use the `then()` method – Yousaf Sep 08 '21 at 10:03

0 Answers0