Search code examples
javascriptpromisewait

JS Promises - how to make a axios call wait?


Here is what I am trying to accomplish. In my app I want to check if a some data has been previously loaded up (from an API call elsewhere in the app). If not, then I want to load the data up. However, I don't want to go any further in the app until I am assured that I have the data.

So the pseudocode looks like this.

if (!dataIsloaded) {
  axios.get("/api/getData").then((data) => {
    saveData(data); 
    dataIsLoaded=true;
  });
}

// don't go any further until I'm assured I have the data

Can someone provide a code snippet how to accomplish this? Thanks!


Solution

  • You don't have to wait, simply run your processing after the data are there:

    if (!dataIsloaded) { // First retrieve the data
        axios.get("/api/getData").then((data) => {
            saveData(data); 
            dataIsLoaded=true;
            doSomethingWithTheData(data); // Finally use the data
        });
    }
    else { // Directly use the data
        doSomethingWithTheData(data);
    }
    
    ...
    
    function doSomethingWithTheData(data) {
        ...
    }