מצטרף לתשובה הפופולרית - Promises. יש ב JS פקודת await שמחכה לביצוע Promise, ואפשר ללכת בשני כיוונים:
1. אם הסדר חשוב נבצע כל Promise ואז נתחיל את הבא אחריו. זה יראה בערך כך:
קוד: |
// define an array of urls
const urls = [...];
function downloadAllInOrder() {
for (let url of urls) {
const res = await fetch(url);
const body = await res.text();
console.log(body);
}
}
|
2. אם הסדר לא חשוב אפשר ליצור Promise יחיד מכל המערך ואז כל הבקשות מבוצעות במקביל. זה יראה בערך כך:
קוד: |
// define an array of urls
const urls = [...];
function downloadAllInOrder() {
const responses = await Promise.all(urls.map(fetch));
const bodies = await Promise.all(responses.map(r => r.text()));
// now bodies is an array of all the responses
console.log(bodies[2]);
}
|
לא בדקתי אף אחת מהפונקציות אז ייתכנו אי דיוקים.