Home > Software engineering >  Calling function multiple times inside while loop
Calling function multiple times inside while loop

Time:03-27

I am trying to get data from a function call and I am keeping it in a while loop so the function will be called again and again if data is not received. When I console the data from getData () it is successfully showing the response but why I am not receiving the data from function calling , is there is any problem with the return statement ? . Please correct my code .

Here is my code :

router.get('/someurl' , async(req,res) => {
let data = [];
while(data.length == 0)
{
  data = await getData()
  console.log(data)
   }
})

Here is how the format of how I am returning those values in functionCall() :

const unirest = require("unirest");
const cheerio = require('cheerio')



 const getData = async() => {
   const data1 = [] , data2 = [] , data3 = [] ;
   try {
   const response = await unirest
   .get('url')
   .headers({'Accept': 'application/json', 'Content-Type': 'application/json'})
   .proxy("proxy")
   const $ = cheerio.load(response.body)
   $('hided').each((i,el) =>
   {
         data1[i] = $(el)
         .find('hided')
         .text()
         data2[i] = $(el)
         .find('hided')
   })
   $('hided').each((i,el) =>
   {
         data3[i] = $(el)
         .find('hided')
         .text()
   })
    if(data1.length && data2.length && data3.length)
    {
      return [data1 , data2 , data3]
    }
   }
      catch(error)
      {
         console.log("Error" , error);
      }
      return [];
      }
 
 
module.exports =  getData

CodePudding user response:

First, don't do that while loop. You just need await the function call.

The problem is that you're not resolving the Promise that you started with unirest call. In a quick google search, I've found that what is missing is a .exec() call that will return the correct Promise that can be awaitable. So:

 const response = await unirest
   .get('url')
   .headers({'Accept': 'application/json', 'Content-Type': 'application/json'})
   .proxy("proxy")
   .exec(); //here will make request awaitable

Remeber to remove that while loop that will make the nodejs event loop block.

CodePudding user response:

I just found there is no problem in code , don't know why it was not returning earlier when I tried , but now it is successfully returning the data .

  • Related