0

I am trying to get some data from an external API, but when I loop am trying to push into an empty array it stills empty. I think it has something to do with accessing the variable inside the callback or the asynchronous behavior.

  const ListProducts = asyncHandler(async response => {
  var array = [];
  response.forEach(p => {
    anExternalAPI.showProducts({
      id: p.id,
      callback: res => {
        console.log(res); // showing data
        array.push(res);
      }
    });
  });
  console.log("products: ", array); // it is empty
  return array;
});
Slim yaw
  • 79
  • 7
  • "*I think it has something to do with […] the asynchronous behavior*" - precisely that. – Bergi Jan 27 '20 at 20:08
  • What is the solution please? I tried to put the sync code in setTimeout 1000ms and it worked but I don't think this is a good thing to do. – Slim yaw Jan 27 '20 at 20:26

0 Answers0