0

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();
}

2 Answers2

1

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;
}
Barmar
  • 741,623
  • 53
  • 500
  • 612
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.

Ricky
  • 763
  • 3
  • 7
  • 29