Middle+
/** * A função `asyncAuth(callback)` aceita um callback, no qual podem ser * passados um 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() { return new Promise((resolve, reject) => { asyncAuth((error, data) => { if (error) { reject(error) } else { resolve(data) } }); }) } /** * A função `tryAuth()` usa `auth()` e, em caso de erro, * realiza N tentativas adicionais. * Se todas falharem, devolve o último erro. * * @returns {Promise} */ function tryAuth(n) { }
sobes.tech IA
Resposta da IA
A função tryAuth deve chamar auth() e, em caso de erro, tentar novamente até N vezes. Se todas as tentativas falharem, devolver o último erro. Aqui está um exemplo de implementação usando async/await:
async function tryAuth(n) {
let lastError;
for (let i = 0; i < n; i++) {
try {
const data = await auth();
return data; // Resultado bem-sucedido
} catch (error) {
lastError = error; // Guardar o erro
}
}
throw lastError; // Todas as tentativas falharam
}
Se não usar async/await, pode implementar através de uma cadeia de promessas, mas async/await torna o código mais legível.