0

I have a block of code that calls an Api and saves results if there are differences or not. I would like to return different values for DATA as layed out on the code. But this is obviously not working since Its returning undefined.

let compare = (term) => {
let DATA;
//declare empty array where we will push every thinkpad computer for sale.
let arrayToStore = [];
//declare page variable, that will be the amount of pages based on the primary results
let pages;
//this is the Initial get request to calculate amount of iterations depending on result quantities.
axios.get('https://api.mercadolibre.com/sites/MLA/search?q='+ term +'&condition=used&category=MLA1652&offset=' + 0)
.then(function (response) {
 //begin calculation of pages
 let amount = response.data.paging.primary_results;
 //since we only care about the primary results, this is fine. Since there are 50 items per page, we divide
 //amount by 50, and round it up, since the last page can contain less than 50 items
 pages = Math.ceil(amount / 50);

 //here we begin the for loop.
 for(i = 0; i < pages; i++) {
    // So for each page we will do an axios request in order to get results
    //Since each page is 50 as offset, then i should be multiplied by 50.
    axios.get('https://api.mercadolibre.com/sites/MLA/search?q='+ term +'&condition=used&category=MLA1652&offset=' + i * 50)
    .then((response) => {
        const cleanUp = response.data.results.map((result) => {
            let image = result.thumbnail.replace("I.jpg", "O.jpg");
             return importante = {
                id: result.id,
                 title: result.title,
                 price: result.price,
                 link: result.permalink,
                 image: image,
                 state: result.address.state_name,
                 city: result.address.city_name
            }
        });
        arrayToStore.push(cleanUp);
        console.log(pages, i)
        if (i === pages) {
            let path = ('./compare/yesterday-' + term +'.json');


                if (fs.existsSync(path)) {
                    console.log("Loop Finished. Reading data from Yesterday")
                    fs.readFile('./compare/yesterday-' + term +'.json', (err, data) => {
                        if (err) throw err;
                        let rawDataFromYesterday = JSON.parse(data);
                        // test
                        //first convert both items to check to JSON strings in order to check them.
                        if(JSON.stringify(rawDataFromYesterday) !== JSON.stringify(arrayToStore)) {
                            //Then Check difference using id, otherwise it did not work. Using lodash to help.
                            let difference = _.differenceBy(arrayToStore[0], rawDataFromYesterday[0],'id');
                            fs.writeFileSync('./compare/New'+ term + '.json', JSON.stringify(difference));
                            //if they are different save the new file.
                            //Then send it via mail
                            console.log("different entries, wrote difference to JSON");
                            let newMail = mail(difference, term);
                            fs.writeFileSync('./compare/yesterday-' + term +'.json', JSON.stringify(arrayToStore));
                            DATA = {
                                content: difference,
                                message: "These were the differences, items could be new or deleted.",
                                info: "an email was sent, details are the following:"
                            }
                            return DATA;
                        } else {
                            console.log("no new entries, cleaning up JSON"); 
                            fs.writeFileSync('./compare/New'+ term + '.json', []);
                            DATA = {
                                content: null,
                                message: "There were no difference from last consultation",
                                info: "The file" + './compare/New'+ term + '.json' + ' was cleaned'
                            }
                            return DATA;
                        }

                    });
                } else {
                    console.error("error");
                    console.log("file did not exist, writing new file");
                    fs.writeFileSync('./compare/yesterday-' + term +'.json', JSON.stringify(arrayToStore));
                    DATA = {
                        content: arrayToStore,
                        message: "There were no registries of the consultation",
                        info: "Writing new file to ' " +  path + "'"
                    }
                    return DATA;
                }






        }

    })
 }  

}).catch(err => console.log(err));





}


    module.exports = compare

So I export this compare function, which I call on my app.js. What I want is to make this compare function return the DATA object, so I can display the actual messages on the front end,

My hopes would be, putting this compare(term) function inside a route in app.js like so:

app.get("/api/compare/:term", (req, res) => {
    let {term} = req.params
    let data = compare(term);
    res.send(data);
})

But as I said, Its returning undefined. I tried with async await, or returning the whole axios first axios call, but Im always returning undefined.

Thank you

Estus Flask
  • 206,104
  • 70
  • 425
  • 565
Martin Ch
  • 39
  • 9
  • ‘compare’ is a big pile of code that is hard to follow. The problem with it is that it doesn’t return the result because promises aren’t chained properly. You can’t efficiently chain them with ‘for’. Try to rewrite it to pure async..await with no ‘then’, then you’ll be able to await for it in route handler. This is a case of https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call – Estus Flask Mar 14 '20 at 21:46
  • @EstusFlask Thank you. I solved it by splitting up my code into various different async functions. It was tough. The for loop of promises I solved it using this: [from stack overflow](https://stackoverflow.com/questions/56532652/axios-get-then-in-a-for-loop), I think I spent about 8 hours refactoring my code, but now I get a correct return on each of the three cases I have, while successfuly writing to disk. Later on Ill post the refactor. – Martin Ch Mar 16 '20 at 12:20

0 Answers0