0

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.

14
  • express wants standard functions async functions are standard functions, the only difference is they return a promise, and you can use them in middleware's in expresss. Commented May 9, 2023 at 15:43
  • I mean express.use() isn't taking in any promises for arguments. So i have to settle the request operation within each iteration. How? Commented May 9, 2023 at 15:57
  • What do you mean expess.use isn't taking any promises as arguments,.. This will work -> express.use(async (req, res, next) => { .... await something().. etc Commented May 9, 2023 at 15:58
  • 1
    IT WORKS !! Thanks a lot. Damn 1 async function and the whole code branches off into asyncs. What if I wanted to synchronously run the code after the request ? Commented May 9, 2023 at 16:16
  • 1
    request and request-promise have been deprecated for many years by the way. You must have seen those in old tutorials. It's best to read more recent materials. Commented May 9, 2023 at 22:13

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.