Sobes.tech
Middle+

/** * Funkcija `asyncAuth(callback)` prihvata callback, u koji * se može proslediti greška (kao prvi argument) i podaci * sa backend-a (kao drugi argument). * asyncAuth((error, data) => {}); * * Potrebno je da implementirate funkciju `auth()`, * koja poziva `asyncAuth()`, ali vraća Promise. * * @returns {Promise} */ function auth() { return new Promise((resolve, reject) => { asyncAuth((error, data) => { if (error) { reject(error) } else { resolve(data) } }); }) } /** * Funkcija `tryAuth()` koristi `auth()` i, u slučaju greške, * pravi N dodatnih pokušaja. * Ako svi ne uspeju, vraća poslednju grešku. * * @returns {Promise} */ function tryAuth(n) { }

sobes.tech АИ

Одговор од АИ

Funkcija tryAuth treba da pozove auth() i u slučaju greške da pokuša ponovo do N puta. Ako svi pokušaji ne uspeju, vratiti poslednju grešku. Evo primera implementacije koristeći async/await:

async function tryAuth(n) {
  let lastError;
  for (let i = 0; i < n; i++) {
    try {
      const data = await auth();
      return data; // Uspešan rezultat
    } catch (error) {
      lastError = error; // Pamti grešku
    }
  }
  throw lastError; // Svi pokušaji nisu uspeli
}

Ako ne želite da koristite async/await, možete ga implementirati putem lanca promise-a, ali async/await čini kod čitljivijim.