Why can’t I access the variable outside the while loop in Node.js?

Asked

Viewed 22 times

0

I have a module that takes public information from the TJPB from the number of a process. This information can be at any of nine different addresses. Therefore, I make requests to each of these addresses, using the axios, and store the response in the variable answer. Since only one of the routes will contain the information, at each loop, I check the content of answer.data, stopping the execution as soon as it contains something. For this, consider:

const axios = require('axios')

async function Pesquisa () {

    let count = 1

    const numProcesso = '08028441420208150221'

    while (count < 10) {
        console.log(`executando vez: ${count}`)
    
        let url = `https://esb.tjpb.jus.br/cp-backend/sistemas/${count}/processos/${numProcesso}`
    
        let answer = await axios.get(url);

        if (answer.data !== '') {
            console.log('if atendido, answer.data: ')
            console.log(answer.data)
            break
        }
        
        count++;
    }
    console.log('while encerrado, answer.data: ')
    console.log(answer.data)
}

Pesquisa()

Notice that inside the while, axios.data is accessible, but once the loop is closed, I get the following error when I try to access this data:

(node:23512) UnhandledPromiseRejectionWarning: ReferenceError: answer is not defined

Can you explain to me why this is happening? What exactly JavaScript or the axios are doing behind the scenes that causes this mistake?

  • 1

    Hello Yoyo, in these answers has the explanation of how the let works: https://answall.com/q/47165/3635 and https://answall.com/q/279182/3635... Taking advantage of a similar case, but caused by another situation, however it helps to understand certain conflicts: https://answall.com/q/484513/3635. Good reading, I hope it helps. If you have any specific doubts just [Dit] the question and modify it.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.