Middle
/** * Funkce `asyncAuth(callback)` přijímá callback, do kterého * může být předána chyba (prvním argumentem) a data * ze backendu (druhým argumentem). * asyncAuth((error, data) => {}); * * Musíte implementovat funkci `auth()`, * která volá `asyncAuth()`, ale vrací Promise. * * @returns {Promise} */ function auth() { // asyncAuth((error, data) => {}); } /** * Funkce `tryAuth()` používá `auth()` a v případě chyby, * provádí N dalších pokusů. * Pokud všechny selžou, vrátí poslední chybu. * * @returns {Promise} */ function tryAuth(n) { }
sobes.tech AI
Odpověď od AI
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` раз в случае ошибки, и если все попытки неудачны, выбрасывает последнюю ошибку.