Middle+
/** * La funzione `asyncAuth(callback)` accetta un callback, nel quale può * essere passato 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() { return new Promise((resolve, reject) => { asyncAuth((error, data) => { if (error) { reject(error) } else { resolve(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
La funzione tryAuth deve chiamare auth() e, in caso di errore, riprovare fino a N volte. Se tutti i tentativi falliscono, restituire l'ultimo errore. Ecco un esempio di implementazione usando async/await:
async function tryAuth(n) {
let lastError;
for (let i = 0; i < n; i++) {
try {
const data = await auth();
return data; // Risultato riuscito
} catch (error) {
lastError = error; // Memorizza l'errore
}
}
throw lastError; // Tutti i tentativi falliti
}
Se non si vuole usare async/await, si può implementare tramite una catena di promesse, ma async/await rende il codice più leggibile.