1

I am trying to update user data in multiple tasks collection. So I have multiple id's of tasks, where I use forEach loop reading each of task. In each task I have multiple users where I want to update only one specific user.

I am using firestore and batch for writing data. The problem is that only last task is updated. This is my code

tasksIds.forEach(async function(taskId) {
 
                
                const batch = db.batch()

                try {
                    taskRef =  db.collection("tasks")
                        .doc(taskId)
                    const projectDataTemp = await taskRef.get()
                    projectData=  projectDataTemp.data()
                    allClients = projectData.users
                } catch (error) {
                    console.log(error)
                
                await allClients.map(async (oneClient) => {
                    if(oneClient.id === id) {
                        oneClient.name = name
                    }

                })

                    
                    await batch.update(taskRef, { users: allClients})
                
                // Commit the batch
                 await batch.commit().then(() => console.log("success",allClients))
        
            })
        }

So everything is good except that only last task is updated, I suppose that the problem is of synchronisation that batch.commit isn't finished and another task is started. Anyone idea how to solve this?

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
HardRock
  • 809
  • 2
  • 12
  • 37
  • 1
    It might be helpful if you add some logging that shows how your code is executing, and share that specific output so we can see what's actually happening. – Doug Stevenson Oct 25 '20 at 15:48
  • The problem is `const projectDataTemp = await taskRef.get()` here await waits until data is fetched, in meantime loop goes on, and in the end only last one is updated – HardRock Oct 25 '20 at 22:00
  • async/await does not work in a forEach loop in the way you expect. I suggest reading this: https://stackoverflow.com/questions/37576685/using-async-await-with-a-foreach-loop – Doug Stevenson Oct 25 '20 at 22:17
  • Thank you for pointing me in right direction, using standard for loop solved my problem – HardRock Oct 26 '20 at 07:23

1 Answers1

1

If you want to read the files in sequence, you cannot use forEach indeed. Just use a modern for … of loop instead, in which await will work as expected:

async function printFiles () {
  const files = await getFilePaths();

  for (const file of files) {
    const contents = await fs.readFile(file, 'utf8');
    console.log(contents);
  }
}

Changing forEach loop for standard one, solved problem.

Thank you @DougStevenson for pointing me in right direction

HardRock
  • 809
  • 2
  • 12
  • 37