Sobes.tech
Middle

/** * La funzione `asyncAuth(callback)` accetta un callback, nel quale * può essere passata un errore (come primo argomento) e dati * dal backend (come secondo argomento). * asyncAuth((error, data) => {}); * * Devi implementare la funzione `auth()`, * che chiama `asyncAuth()`, ma restituisce una Promise. * * @returns {Promise} */ function auth() { // asyncAuth((error, data) => {}); } /** * La funzione `tryAuth()` utilizza `auth()` e, in caso di errore, * effettua N tentativi aggiuntivi. * Se tutti falliscono, restituisce l'ultimo errore. * * @returns {Promise} */ function tryAuth(n) { }

sobes.tech AI

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