Sobes.tech
Middle

/** * Funkcia `asyncAuth(callback)` prijíma callback, do ktorého * môže byť odovzdaná chyba (ako prvý argument) a údaje * zo backendu (ako druhý argument). * asyncAuth((error, data) => {}); * * Musíte implementovať funkciu `auth()`, * ktorá volá `asyncAuth()`, ale vracia Promise. * * @returns {Promise} */ function auth() { // asyncAuth((error, data) => {}); } /** * Funkcia `tryAuth()` používa `auth()` a v prípade chyby, * robí N ďalších pokusov. * Ak všetky zlyhajú, vráti poslednú chybu. * * @returns {Promise} */ function tryAuth(n) { }

sobes.tech AI

Odpoveď 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` раз в случае ошибки, и если все попытки неудачны, выбрасывает последнюю ошибку.