à expliquer :
Pour attendre le succès de plusieurs promesses d'un coup, on utilise Promise.all().
Un exemple d'utilisation qui s'occupe de :
async function synced_json_fetch(urls = [], callback) { promises = []; // start fetching each url // we don't store the fetch promises, we juste use it right away (asynchronously, of course) to start to parse its Json // we store json parsing promises into a new array request_urls.forEach(url => promises.push( fetch(url).then(function(response) { return response.json(); }) )) // we use a single then() for multiple promises (that way, we make them sync, meaning we will wait for the last of them to finish before calling the callback function) return Promise.all(promises).then(callback); } // exemple of use request_urls = [ "http://url1", "http://url2", "http://url3" ]; synced_json_fetch(request_urls, function(values) { // code executed only when every url fetching and parsing will be done console.log(values); }); // other way to call it, using then on the returned promise synced_json_fetch(request_urls).then(function(values) { // code executed only when every url fetching and parsing will be done console.log(values); });
Il y a d'autres approches aux Promises multiples, plutôt que le Promise.all() : Promise.allSettled() ou Promise.race(), par exemple (page en anglais expliquant les différences).