0

I am facing this weird issue where the content of my array variable is available in nested functions, but not on the same level where it was declared?

  const add_opted_out = (req, res) => {
          var opted_out = new Array()
          axios.get(url).then((res) => {
            parseString(res.data, (err, result) => {
            opted_out.push('a')
            // prints members
            console.log(opted_out)
            })
          }).catch((err) => {
            console.log(`error occured: ${err}`)
          })
          // prints nothing
          console.log(opted_out)

Why is this behaviour?

richardthefourth
  • 123
  • 1
  • 3
  • 8

1 Answers1

2

The code to populate opted_out is asynchronous. Your console.log that prints nothing actually executes BEFORE opted_out is populated.

Your function within the .then call is executed when the server responds to your request.

UncleDave
  • 6,872
  • 1
  • 26
  • 44
  • How can I use res.render then, if I need to use it within a callback function? – richardthefourth Jan 12 '18 at 16:18
  • There should be no problem using `res.render` within a `.then` callback. A potential issue with your current setup is you have two variables called `res`. You should rename one of them. – UncleDave Jan 12 '18 at 16:20