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
Для преобразования функции с callback в Promise можно использовать конструктор Promise и внутри вызвать asyncAuth.
function auth() {
return new Promise((resolve, reject) => {
asyncAuth((error, data) => {
if (error) {
reject(error);
} else {
resolve(data);
}
});
});
}
Для tryAuth(n) нужно попытаться вызвать auth() до n раз, пока не будет успешного результата, или вернуть последнюю ошибку:
async function tryAuth(n) {
let lastError;
for (let i = 0; i < n; i++) {
try {
const data = await auth();
return data; // успех
} catch (error) {
lastError = error;
}
}
throw lastError; // все попытки провалились
}
Такой подход позволяет использовать async/await для удобства и повторять попытки при ошибках.