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
Для преобразования функции с 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 для удобства и повторять попытки при ошибках.