-1

I have an async loop that checks an array and if a specific value is found, it loops another array to match the founded value.

So my first implementation. I open an async loop and get my Data from Database

mergedObject = [];
 array1.forEach(async (item) => {
  if (item.id == 'XXX') {
   const dbInfo = await readDB();

The db infos, i want to push into a array and build a json object.

      dbInfo.forEach(async (itemDB) => {
    object.push({
      id,
      name,
      ..
      ..

At the end of the loop I merge the new Object with an "older" object

  mergedObject = _.map(oldObject, (objs) => {
    _.assign(objs, _.find(object, {
      id: objs.id,
    }));
  });

The Problem I have is, that inside the forEach I get the log correctly. But If I want use the mergedObject outside the forEach (array1) I get log: []

This is my first try with async. I used Callbacks before. How can I access the mergedObject outside the forEach's?

Ckappo
  • 607
  • 1
  • 9
  • 27
  • Please create a [mcve] – baao Jun 25 '18 at 13:06
  • You shouldn't use forEach or other function-based iteration APIs with async..await, unless you know what you're doing. Loop statements like for..of naturally support async..await. There's a bunch of 'forEach vs for' dupe questions on SO. – Estus Flask Jun 25 '18 at 13:20
  • 1
    Possible duplicate of [Using async/await with a forEach loop](https://stackoverflow.com/questions/37576685/using-async-await-with-a-foreach-loop) – Estus Flask Jun 25 '18 at 13:21

1 Answers1

5

Async/await wont work on forEach. use for in, for of or traditional for loop. refer this Using async/await with a forEach loop

SAGAR RAVAL
  • 319
  • 1
  • 9