I have a set of values in a mongoDB I need to only be read ones. So when I have read them I delete that line from the DB. But since node is async if I do getValue() twice in quick succession I get the same value, since the DB has not had time to delete the old one. Does anyone know a good way to fix this problem. I can think of a couple but nothing good.
I don’t have my code here so just wrote a quick example to show my problem.
Var getValue = function() {
ReadfromDB(function(data){
deleteRecord(); // show that what we read has been updated
});
}
You could try something like this. The reading is placed into a promise that's done when the deleting is done as well. This can stack so if you do getValue()
20 times it still should execute in the correct order.
var getValue = function(){
var currentPromise;
var read = function(){
return ReadfromDB().then(function(data){
deleteRecord(); // show that what we read has been updated
});
}
return function() {
if(currentPromise){
currentPromise = currentPromise.then(read)
}else{
currentPromise = read();
}
}
}
What you need to do outside this code is make sure ReadfromDB
returns a promise object.
Sounds like a good use case for a closure!
var getValue = (function() {
var called = false;
return function() {
if (!called) {
called = true;
ReadFromDB(function(data) {
deleteRecord();
});
}
};
}());
You could also use once to do exactly the same thing.
var once = require('once');
var getValue = once(function() {
ReadFromDB(function(data) {
deleteRecord();
});
});