Looping while receiving data from async request module

51 Views Asked by At

I am a newbie in Node.JS. I am trying to fetch data from an api and filtering out data from a miscellaneous response. But my while loop is getting into infinite loop as the res array never gets populated due asynchronous behavior of request.

let res=[];
    while(res.length<=10){
        request(searchLink.apiLink, (err, response, body)=>{
            console.log("Agregation complete!");
            if(err){
                throw new Error("Api response error detected : ", err);
            }else{
                body=JSON.parse(body);
                for(let i=0; i<body.results.length; i++){
                    var cond=body.results[i].title!=null && body.results[i].description!=null && body.results[i].content!=null && body.results[i].language=="english";
                    if(cond) res.push(body.results[i]);
                }
                searchLink.apiLink+=`&page=${body.nextPage}`;
            }
        });
    }

Promisifying and awaiting is not quite solving the problem as express wants standard functions for middleware and not promises. And as far as I know top level await should be allowed to settle the request but Node is throwing syntax errors.

0

There are 0 best solutions below