Middle
/** * Funkcija `asyncAuth(callback)` prihvata callback, u koji * može biti prosleđena greška (kao prvi argument) i podaci * sa backend-a (kao drugi argument). * asyncAuth((error, data) => {}); * * Potrebno je implementirati funkciju `auth()`, * koja poziva `asyncAuth()`, ali vraća Promise. * * @returns {Promise} */ function auth() { // asyncAuth((error, 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 АИ
Одговор од АИ
javascript function auth() { return new Promise((resolve, reject) => { asyncAuth((error, data) => { if (error) { reject(error); } else { resolve(data); } }); }); }
async function tryAuth(n) { let lastError; for (let i = 0; i <= n; i++) { try { const result = await auth(); return result; } catch (error) { lastError = error; if (i === n) { throw lastError; } } } }
Функция `auth()` оборачивает вызов `asyncAuth` в Promise, чтобы использовать современный синтаксис async/await. Функция `tryAuth(n)` пытается вызвать `auth()` до `n` раз в случае ошибки, и если все попытки неудачны, выбрасывает последнюю ошибку.