Sobes.tech
Middle+

Backenddan ma'lumot so'rovlar uchun batchFetch funksiyasi bilan qoplangan smartFetch funksiyasini amalga oshiring. Funksiya vaqt oynasi (timeout) davomida chaqiruvlarni to'plab, ularni bitta partiyaviy so'rov bilan yuborishi kerak. Keyingi oynani kutish, so'rov yuborilganidan keyin darhol boshlanadi. IDlar unikal, fetch har doim muvaffaqiyatli. Bir oynada takrorlanuvchi IDlar kelgan holatni to'g'ri ishlash zarur.

sobes.tech AI

AIdan javob

javascript function smartFetch(batchFetch, timeout) { let queue = new Map(); // id -> [resolve, reject] let timer = null;

function flush() { const ids = Array.from(queue.keys()); const resolvers = Array.from(queue.values()); queue = new Map(); timer = null;

batchFetch(ids).then(results => {
  // results - array of data in the same order as ids
  results.forEach((result, index) => {
    resolvers[index].resolve(result);
  });
});

}

return function(id) { return new Promise((resolve, reject) => { if (!queue.has(id)) { queue.set(id, {resolve, reject}); } else { // Agar id allaqachon mavjud bo'lsa, boshqa resolve qo'shish uchun const old = queue.get(id); // Agar kerak bo'lsa, massivga aylantiring if (Array.isArray(old)) { old.push({resolve, reject}); queue.set(id, old); } else { queue.set(id, [old, {resolve, reject}]); } }

  if (!timer) {
    timer = setTimeout(flush, timeout);
  }
});

}; }