0

Here's my code,I am getting the latLongData array without the Objects. How to resolve it? What could be the possible reason?

let latLongData = [];
async function calcLatLong() {
  let Obj = {
    loadId: locPoints.loadId,
    latLongs: []
  };
  try {
    for (let point of locPoints.loadingUnloadingPoints) {
      if (point.location) {
        Obj.latLongs.push(await getLatLong(point.location));
      }
    }
    latLongData.push(Obj);
  } catch (err) {
    throw new Error(err);
  }
  return latLongData;
}

Even after using for..of instead of forEach loop the problem persists.

  • 1
    post the code where you call this function – Sudhakar Ramasamy Oct 12 '19 at 12:59
  • 1
    I think this can be useful (https://stackoverflow.com/questions/37576685/using-async-await-with-a-foreach-loop/37576787) for your problem – harshilparmar Oct 12 '19 at 13:02
  • 1
    Possible duplicate of [Using async/await with a forEach loop](https://stackoverflow.com/questions/37576685/using-async-await-with-a-foreach-loop) – laggingreflex Oct 12 '19 at 13:16
  • Can I solve the problem using Generators? @laggingreflex –  Oct 12 '19 at 13:46
  • You added "Even after using `for..of` instead of `forEach` loop the problem persists.". Could you add the exact code how you used for..of? It should've worked. – laggingreflex Oct 12 '19 at 13:51
  • Sure, @laggingreflex. I have made the relevant changes in the code. –  Oct 12 '19 at 13:55
  • Seems like it should work. Could you add what data are you expecting VS what are you actually getting? – laggingreflex Oct 12 '19 at 14:07
  • I am expecting data resolved by the API that I have called and pushed into the array. It is simply that the function is returning before the data gets resolved. –  Oct 12 '19 at 14:35
  • for..do is very slow and taking much time. Please suggest some alternatives. @laggingreflex I will be grateful to you. –  Oct 12 '19 at 14:42
  • @BinayakGS There was also another suggestion `Promise.all` in the answer linked above, try that. – laggingreflex Oct 12 '19 at 14:56
  • Both types of for loops are fine in async functions. Only functional solutions like forEach are problematic. – Tom Boutell Oct 12 '19 at 15:14

0 Answers0