Middle
/** * A função `asyncAuth(callback)` aceita um callback, no qual * pode ser passada uma erro (como primeiro argumento) e dados * do backend (como segundo argumento). * asyncAuth((error, data) => {}); * * Precisa implementar a função `auth()`, * que chama `asyncAuth()`, mas retorna uma Promise. * * @returns {Promise} */ function auth() { // asyncAuth((error, data) => {}); } /** * A função `tryAuth()` usa `auth()` e, em caso de erro, * realiza N tentativas adicionais. * Se todas falharem, retorna o último erro. * * @returns {Promise} */ function tryAuth(n) { }
sobes.tech IA
Resposta da IA
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` раз в случае ошибки, и если все попытки неудачны, выбрасывает последнюю ошибку.