0

I have a javascript function as following

async function createGrid(data){ 
   let textArray = [];
   var lang = "eng";
   data.map(async obj => {
    await getTranslatedText(lang, obj.type).then(res =>{
            textArray.push(res);
        });
    });

   console.log(textArray);
}

and also getTranslatedText return a string value.

from the console log below it will print the array as empty. When I extract it, it will show us the data in it.

Can anyone explain what is happening here and how we can get the values?enter image description here

Mad
  • 41
  • 8
  • Typical async problem. Your code is simply jumping to `console.log(textArray)`, before the above async operations are ready. Try using a regular `for` for example instead of the `map` and you will see your array filled at the point of the `console.log` – codtex Mar 02 '23 at 08:40
  • For why the data appears to be there when you extract it: [Weird behavior with objects & console.log](https://stackoverflow.com/questions/23429203/weird-behavior-with-objects-console-log) – Ivar Mar 02 '23 at 08:41
  • Relevant (it contains TypeScript, but that shouldn't really matter): [Use async await with Array.map](https://stackoverflow.com/questions/40140149/use-async-await-with-array-map) – Ivar Mar 02 '23 at 08:42
  • Unrelated: Use `forEach` instead of `map` when you discard the returned value. Or `const textArray = await Promise.all(data.map(obj => getTranslatedText(lang, obj.type)));` – jabaa Mar 02 '23 at 09:57

0 Answers0