Firestore not writing all documents

Viewed 104

I'm using forEach to write over 300 documents with data from an object literal.

It works 80% of the time -- all documents get written, the other times it only writes half or so, before the response gets sent and the function ends. Is there a way to make it pause and always work correctly?

Object.entries(qtable).forEach(([key, value]) => {

    db.collection("qtable").doc(key).set({
            s: value.s,
            a: value.a

    }).then(function(docRef) {
            console.log("Document written with ID: ", docRef.id);

    res.status(200).send(qtable);
    return null;
})

Would it be bad pratice to just put a 2 second delay?

2 Answers

You are sending the response inside your loop, before the loop is complete. If you are using Cloud Functions (you didn't say), sending the response will terminate the function an clean up any extra work that hasn't completed.

You will need to make sure that you only send the response after all the async work is complete. This means you will have to pay attention to the promises returned by set() and use them to determine when to finally send the response. Leaning how promises work in JavaScript is crucial to writing functions that work properly.

You need to wait for the set() calls to conclude. They return a promise that you should deal with.

For instance, you can do this by pushing the return of set() to a promise array and awaiting for them outside the loop (with Promise.all()).

Or you can await each individual call, but in this case you need to change the forEach() to a normal loop, otherwise the await will not work inside a forEach() arrow function.

Also, you should probably set the response status just once, and outside the loop.

Related