0

I'm simply using https.get to retrieve a URL response code, but I don't want to just show it in the console, I want to store it in array to later insert it in a DB table. Here's what I'm doing:

results.forEach((element, index) => {
 link[index] = element.AppURLAndroid;
 https.get(link[index], function(res) {
   resCode[index] = res.statusCode;
  }).on('error', function(e) {
  console.error(e);
  });                
});

As you can see, I'm retrieving the URLs from an array, getting the response code, and trying to store it in another array. The problem relies in this line resCode[index] = res.statusCode; .. if I do console.log it works fine and I can see the response code, but somehow I just can't assign it into a variable or array. I also tried using a global variable like global.resCodeTemp, but it also doesn't work. What am I doing wrong?

Thank you.

[EDIT] : there are no error thrown, I just try to print the array after the insertion and the array is empty.

Tariq
  • 59
  • 6
  • Describe properly why you can't assign to variable. Is it throwing error or not stored properly? – Harsh Kanjariya Sep 23 '21 at 11:01
  • No it doesn't throw any errors, nothing happens, I just try to print the array and it's empty. If there were any errors or more detailed I would've put them. – Tariq Sep 23 '21 at 11:03
  • 1
    Does this answer your question? [How to return the response from an asynchronous call](https://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call) – CBroe Sep 23 '21 at 11:08

1 Answers1

1

Can you please try below code. In below code I have pass index in function to use in rescode.

results.forEach((element, index) => {
 link[index] = element.AppURLAndroid;
 https.get(link[index], function(res,index) {
   resCode[index] = res.statusCode;
  }).on('error', function(e) {
  console.error(e);
  });                
});
Hkachhia
  • 4,463
  • 6
  • 41
  • 76