I'm looking for a mutex in object editing for javascript.
The exact problem is this : I'm reading asynchronously from several files. and collecting info to a single object. This can get down to this toy-example
var o = {};
files_list.forEach(function(fpath){fs.readFile(fpath,
function(err,content){
var k = Math.floor((Math.random()*10)+1);
if(o[k])
{o[k].push(content);}
else
{o[k]=[content];}
}
);
As I understand it, since readFile is asynchronous, several files might be opened at once.
So what I want is to make access to object o mutually exclusive in each reading callback, so that two simultaneous readings won't mess it up.
What is the way to guarantee that with javascript ? (except for synchronous reading)
(explicit answer given here below)