mardi 24 mars 2015

make a async calls inside a for synchroniously


I am having some trouble with asynchronous events in sails.js.


I'am trying to write something into my database inside a for loop. Everything needs to be executed one after another (in the correct order). To keep the example simple lets just say i am trying to do the following:



//let apiNames be a JSON that contains some names in that order: James, Betty, Jon
//let Customer be a DB which contains that names and related age

for(index in apiNames){
console.log("Searching for "+apiNames[index]+" in the Database...);
Customer.find({name:apiNames[index]}).exec(function(err,customerData){
console.log("Found "+apiNames[index]+" in the Database!");
console.log(customerData);
});
}


The suggesting log should look like this:



Searching for James in the Database....
Found James in Database!
{name:James, age:23}

Searching for Betty in the Database....
Found Betty in Database!
{name:Betty, age:43}

Searching for Jon in the Database....
Found Jon in Database!
{name:Jon, age:36}


Since Javascript is running asynchronously and the DB call is taking to long, the output looks something like this:



Searching for James in the Database....
Searching for Betty in the Database....
Searching for Jon in the Database....
Found James in Database!
{name:James, age:23}
Found Betty in Database!
{name:Betty, age:43}
Found Jon in Database!
{name:Jon, age:36}


I already tried several things to force the loop working synchronously, but nothing worked. AFAIK if i call something inside exec, it should run synchronously (By Chaining it with another exec), but my problem is, that its already failing working synchroniously at the loop. Does anyone have a solution for this and could explain it a bit?





Aucun commentaire:

Enregistrer un commentaire