Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

226
Vistas
Not catching an error from async await despite using try catch blocks

I'm using a loop to get all whatsapp messages associated with given numbers, using whatsappweb-js. When there is error in this line "let chat = await client.getChatById(nums[i])" I'm not able to catch it , instead I get an error refering to the next line stating that "chat is not defined"! if I remove try catch I don't get any errors but the node js application just stop responding note: client.getChatById(id) return a promise containing chat object.

function fetch(nums) {
    for (let i = 0; i < nums.length; i++) {
        try {
            let chat = await client.getChatById(nums[i])
        } catch (err) {
            console.log(err)
        };
    }
    return msgs = await chat.fetchMessages();
}
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

The code that uses chat needs to be inside the try block. This is needed for scoping reasons, and also because it doesn't make sense to use chat if the call failed.

Also, you shouldn't have return inside the loop, since you want to collect the results from all the chats. Declare an array to hold them, add to the array in the loop, then return at the end.

async function fetch(nums) {
  let msgs = [];
  for (let i = 0; i < nums.length; i++) {
    try {
      let chat = await client.getChatById(nums[i]);
      msgs = msgs.concat(await chat.fetchMessages());
    } catch (err) {
      console.log(`while fetching ${nums[i]}`, err)
    };
  }
  return msgs;
}

about 4 years ago · Juan Pablo Isaza Denunciar

0

You need to move the return:

    function fetch(nums) {
  for (let i = 0; i < nums.length; i++) {
    try {
      let chat = await client.getChatById(nums[i])
      return msgs = await chat.fetchMessages();
    } catch (err) {
      console.log(err)
    }; 
  }

Your putting your chat variable outside the try/catch, so it wouldn't know what the variable is.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda