0

I'm currently trying to write a script to be embedded in a HTML file that:

  1. Calls an API for a ticket
  2. Uses the ticket in a subsequent function to display a dashboard

I'm kinda new to Javascript and learning as I go, but I'm getting a bit lost on this one :)

Function1 below shows my efforts to store the ticket as a variable. However, when I try to use the ticket in Function2, it appears that the API call hasn't finished yet.

How can I make Function2 wait for Function1 to complete before processing?

Function1

function getTix() {
    return new Promise(function (resolve) {
        axios.get(api_url)
            .then(response => {
                resolve(response.data.ticket);
                console.log(response.data.ticket);
                myticket = response.data.ticket;
            })
            .catch(error => console.error(error));
    });
}


Function2

function showDashboard() {
    const dash_div = document.getElementById('displaydash');
    const dash_url = "https://server.com/" + myticket;
    
    viz = new Viz(dash_div, dash_url);
}
  • 1
    [What is the explicit promise construction antipattern and how do I avoid it?](https://stackoverflow.com/q/23803743) – VLAZ Feb 01 '22 at 14:56
  • You can do `getTix().then(() => showDashboar())` but it's even better to make `showDashboard` async (`async function showDashboard() {}`) and then inside it call `myticket = await getTix()`. Also, make sure `getTix()` actually returns a value, rather than setting a global. And you can remove the explicit promise constructor from there. – VLAZ Feb 01 '22 at 15:01

0 Answers0