Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

207
Visualizações
fetch().then().catch(); doesn't catch `Uncaught (in promise) DOMException: The user aborted a request.`

I have an interface on an ESP32.
I am trying to have a Connected variable show up in an interface to signal the user if he is connected to said interface or not.

I am using the following method to constantly GET the configuration from the server in order update the interface.

// get json
async function get_json(api_path, options = {}) {
    // const url = api_path;
    // console.log(ROOT_URL);
    // console.log(api_path);
    const { timeout = 8000 } = options;
    const controller = new AbortController();
    const timeoutID = setTimeout(() => controller.abort(), timeout);

    const response = await fetch(api_path, {
        ...options,
        signal: controller.signal,
    });
    clearTimeout(timeoutID);
    return response.json();
}

async function getSettings() {
    get_json("/api/settings/get", {
        timeout: 5000,
    }).then((json_data) => {
        // do something with the data
        connected = true;
    }).catch(function (error) {
        // request timeout
        console.log(error);
        connected = false;
        console.log(error.name === "AbortError");
    });
}

Everything works dandy except the catch part.

Let's say the user changes the IP of the ESP. The ESP restarts and reconfigures to use the newly IP address. But the user stayed on the same page because connected is still set to true. In the console I get Uncaught (in promise) DOMException: The user aborted a request. for each request to getSettings() because I can't write a proper catch.

Basically, after the IP is changed, getSettings() tries to GET from a wrong address, so it's normal to throw some sort of error which I should catch and change the Connected variable to false and update it in the interface so that the user can go/move/navigate to the IP Address they have just inputted.

Edit:

This is how I update connected in the interface:

// check if connected to ESP
function connectedStatus() {
    let conn = document.getElementById("connected");
    conn.innerHTML = connected ? "Yes" : "No";
}

setInterval(connectedStatus, 500);
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

"Doesn't get_json() return a PROMISE?" - All async function does return promise, But your getSettings function doesn't wait for get_json to become resolved.

let delay = ms => new Promise(ok => setTimeout(ok, ms));

async function asyncFn() {
    delay(2000).then(() => {
        console.log("wait! 2 secs...")
    });
    console.log("thanks for waiting")
}
asyncFn()

As you can see "thanks for waiting" print first,

So our guess is that, getSettings indeed modify connected state but not immediately but later, But your getSettings resolve immediately, and you didn't wait for state (connected) change.

So you need to wait for any changes,

let delay = ms => new Promise(ok => setTimeout(ok, ms));

let state;
async function asyncFn() {
  await delay(2000).then(() => {
    state = true
    console.log("wait! 2 secs...")
  });
  console.log("thanks for waiting")
}

asyncFn().then(() => {
  console.log("state:", state)
})

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda