0

I'm a beginner in javascript, but did a lot of googling to figure out promises and async/await. However, it seems like the fetch function call gets called at the end the very end of my program and i don't know how to fix it. I have tried multiple versions of this function from stackoverflow but it seems nothing is giving me the expected result.. What do i do wrong?

This would be my fetch function:

async function fetchData() {
    const resp = await fetch("/test.csv");
    const data = await resp.text();
    return data;
}
function processData(data) {
    console.log(data);
}

Whith this call:

console.log("Before Fetch")
fetchData().then(processData)
console.log("Code after Fetch")

I would expect the following output:

Before Fetch
data
Code after Fetch

But i get:

Before Fetch
Code after Fetch
data

A weird fix would be to put my entire code in the processData(data) function, but there has to be another way i guess?

  • 1
    That is why you pass `processData` as a function to the `.then()`, instead of invoking it separately after `fetchData()`. Because it is a function that is invoked once the response is back in while the rest of the code continues. – Ivar Dec 22 '22 at 11:14
  • 1
    You have come to the point that every beginner needs to face once: understand and get to terms with *asynchronous execution*… – deceze Dec 22 '22 at 11:15
  • Take a look at “await” in asynchronous JavaScript :) – Jordan Dec 22 '22 at 11:15
  • You can refer to this [link](https://stackoverflow.com/a/21518470/19533962) – RKataria Dec 22 '22 at 11:15

0 Answers0