async/await و forEach دادهها را بهصورت غیرهمزمان لود کند، اما رفتار نهایی با انتظار نویسندهی کد فرق دارد و this.data در زمان استفاده هنوز کامل مقداردهی نشده است.سؤال: در این کد چه چیزی باید تغییر کند تا اجرای غیرهمزمان بهدرستی منتظر اتمام تمام درخواستها بماند و سپس
this.data کامل آماده باشد؟class DataLoader {
constructor(apiUrls) {
this.data = [];
this.load(apiUrls);
}
async load(urls) {
urls.forEach(async (url) => {
const res = await fetch(url);
const json = await res.json();
this.data.push(json);
});
}
}
const loader = new DataLoader([
"https://example.com/api/users",
"https://example.com/api/posts"
]);
// بعداً در جایی دیگر:
console.log("Loaded:", loader.data.length); // مقدار اینجا غیرقابل اعتماد است🔖 #Javascript #JS #جاوااسکریپت
👤 Developix
💎 Channel: @DevelopixJavascript
