Burgan
Burgan

Reputation: 900

Wait on two asynchronous functions

The problem I have is that I want to draw a chart based on the data returned from fetch. I know that I could do the following

google.charts.setOnLoadCallback(drawChart);

function drawChart() {
    // get the data and draw the chart after
    fetch(url).then...
}

but, I would like to do something like this

// load google charts
google.charts.setOnLoadCallback(???);
// get the data
fetch(url).???;

// a function that runs after both are complete
drawsChartsAfterBothComplete();

that way the data and the google library can load asynchronously and one doesn't have to wait on the other. Is this possible? If so, how can I do it in my scenario? Thanks

Edit:

I've determined there is no need to use setOnLoadCallback() and that load() returns a promise thanks to the accepted answer.

Upvotes: 1

Views: 126

Answers (1)

tehp
tehp

Reputation: 6394

Promise.all() is probably what you are looking for.

You can run both of those in promises, and run the draw function after they complete.

var p1 = new Promise((resolve, reject) => {
  // load google charts here
}); 

var p2 = new Promise((resolve, reject) => {
  // fetch here
}); 

Promise.all([p1, p2]).then(values => { 
  drawsChartsAfterBothComplete();
});

Upvotes: 4

Related Questions