0
let message; 
let names;

I have two variables. The goal is to initialize them before the rest of the code runs.

async function getArraysFromPHP(phpFile) {
    return fetch('forumData.php')
    .then(response => response.json())
    .then(data => {
      return [data.data, data.data1];
    });
}

I get the data for the two variables (they are two arrays) from this function. This function works.

async function resetForumData() {
    const arrays = await getArraysFromPHP('forumData.php');
    message = arrays[0];
    names = arrays[1];
    console.log(message[0]);
}

I have this function which calls the other one and uses its data to initialize the variables.

resetForumData();

I then call that function to initialize the variables using the data I got from the fetch request.

The problem is that they don't seem to be awaiting. It doesn't call these functions until after the code has been run, which leaves the two variables un-initialized. I am very new to async/await, so I'm not really sure what I'm doing. Thanks for help.

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • You're not using `await` when you call `resetForumData()` so it won't wait for it. Either use `await` or `.then()` – Barmar Dec 08 '22 at 04:40
  • 1
    There's no need to use `async` with `getArraysFromPHP`. `.then()` already returns a promise, you don't need to wrap it in another promise. And you don't use `await` inside the function. – Barmar Dec 08 '22 at 04:42

0 Answers0