Home Wait for mongo writes before returning from a find
 I want a store js object that manages a mongodb collection and behaves like that: store.insert(thing); // called from a pubsub system that don't wait the insert to finish store.get(); // returns a promise that resolves to the things in the collection // even if called immediately after insert it must contain the last thing inserted  I implemented it manually like that: let inserts = 0; let afterInserts = []; const checkInsertsFinished = () => { if (inserts === 0) { afterInserts.forEach(resolve => resolve()); afterInserts = []; } }; const decrementInserts = () => { inserts -= 1; checkInsertsFinished(); }; const insertsFinished = () => new Promise((resolve) => { afterInserts.push(resolve); checkInsertsFinished(); }); const insert = (thing) => { inserts += 1; db.collection('mycollection').insertOne(thing).then(decrementInserts); }; const get = async () => { await insertsFinished(); // if there are inserts happening, wait for them to finish return db.collection('mycollection').find({}).toArray(); }; return { insert, get };  I suppose that there are more standard ways to accomplish this but I miss the vocabulary to find libs or built-in features... How would you do that? Thanks for your advices.