jeudi 2 avril 2015

Parallel write access in Waterline

I'm calling a REST API for updating my database entries in sails. Therefore i have a function which iterates over an JSON Array and calls for each entry another function which saves the values into a database.



function getData(){
for(index in apiJson){
saveData(apiJSON[index]);
}
}


In the saveData function I use the .findOrCreate functionality from waterline. If there is not such an entry a new one is created. This all works pretty fine. But now i want to append the id from the new created entry (Table: match) to an array (matches) in another table (Table: team). There i getting some failures because of the asynchronous behavior of JavaScript.


My implementation (in short) looks like the following:



Match.findOrCreate({..},{..}).exec(function(err,match){
...
//if match was just created in db
if(newMatch){
Team.findOrCreate({apiID: someTeamID}),
{
...
...,
matches: []
}
).exec(function(err,team){
team.matches.push(someID);
team.save(function(err,s){
...
});
});
}
});


Since JavaScript executes this code asynchronously i get duplicate entries of teams in my model Team. Also my array matches in model Team does not correspond to my values in the other model Match.


How can i sort of serialize the database write accesses to prevent this behavior? Is there a possibility to let the loop run in parallel but the database updates in serial?


Aucun commentaire:

Enregistrer un commentaire