等待mongo写入,然后再从find中返回

我想要一个store js对象来pipe理一个mongodb集合并且performance得如此:

 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 

我像这样手动实现它:

 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 }; 

我想有更多的标准方法来完成这个,但我错过词汇来find库或内置function…你会如何做到这一点?

感谢您的build议。

JavaScript是单线程的,你编写的任何代码都不能同时在多个线程上运行,所以你应该可以这样做:

 let inserting = Promise.resolve(), startGetting={}; const insert = (thing) => { startGetting={};//de-reference startGetting inserting = db.collection('mycollection').insertOne(thing) return inserting; }; const get = () => { const rec = () => inserting.then( _ => new Promise( (resolve,reject)=>{ //the next op is truely async (although I wonder why no promise), // someone can insert while this is completing const start=startGetting; db.collection('mycollection').find({}).toArray( (err,results)=> err ? reject(err) //inserting could have been set to tby the time // this completed (in theory) so use startGetting reference equality : startGetting === start ? resolve(results)//while getting nobody inserted : resolve(rec()) ) }) ); return rec(); }; return { insert, get };