in

Issues resetting an array using Node.js when routing an API


This is a dumb question, but I’ve spent alot of time to no success. Basically I’m trying to call a function when making a GET request, but I can’t seem to reset the array it returns as it saves the data from previous calls.

So I have different matrix lists with different topics, and depending on the topic list asked for the function should find titles in articles that match keywords, then return the list of articles to the GET request; however to reiterate, when I reset with “article = []” at the start of the function it always returns an empty matrix.

I know there is nothing wrong with my article.push line, as if I remove the “article=[]” at the start of the function it works, but it saves the articles from the previous GET call.
I feel like this is a really simple issue, but I can’t seem to figure it out.

app.get('/Topic',(req,res) =>{
  
res.json(PullArticle(TopicList1))
})

app.get('/Topic2',(req,res) =>{
  
res.json(PullArticle(TopicList2))
})



function PullArticle (Topic) { 

    article = [] // TRYING TO RESET ARRAY

    Topic.forEach(topic => {
        newspapers.forEach(newspapers =>{
                axios.get(newspapers.address) // pulling html
                .then((response)=>{
                    const html = response.data
                    const $ = cheerio.load(html) //allows to pickout elements
                    $(`a:contains(${topic})`,html).each(function () { 
                        const title = $(this).text()
                        const url = $(this).attr('href')
                        article.push ({
                            title, 
                            url: newspapers.base + url,
                            source: newspapers.name,
                            
                        })
               
                    })
                })
            })
    })
return article
    }



Source: https://stackoverflow.com/questions/70538977/issues-resetting-an-array-using-node-js-when-routing-an-api

A most easily usable improvement rate calculator library in Dart

Simple template suitable for building a webapp backend MVP written in go