I am using a custom model and trying to filter it in a loop using find method. e.g. given below
for i = 0 to n
{
var u = User.find( where { name: 'john'});
}
It doesn't work.
Also, if I use the following
for i = 0 to n
{
User.find( where { name: 'john'}, function(u) {... } );
// How do I call the code for further processing?
}
Is there a way to call find method synchronously ? Please help.
Thanks
I am using a custom model and trying to filter it in a loop using find method. e.g. given below
for i = 0 to n
{
var u = User.find( where { name: 'john'});
}
It doesn't work.
Also, if I use the following
for i = 0 to n
{
User.find( where { name: 'john'}, function(u) {... } );
// How do I call the code for further processing?
}
Is there a way to call find method synchronously ? Please help.
Thanks
Share Improve this question asked Jan 27, 2015 at 14:11 Raj LalwaniRaj Lalwani 3911 gold badge6 silver badges14 bronze badges 2- What exactly do you want to acplish with the loop? – ffflabs Commented Jan 29, 2015 at 14:57
- Try using a promise. Have a look at: howtonode/promises – Sid Commented Mar 13, 2015 at 1:54
3 Answers
Reset to default 2You can solve this using the each function in the async package. Example:
async.each(elements, function(element, callback) {
// - Iterator function: This code will be executed for each element -
// If there's an error execute the callback with a parameter
if(error)
{
callback('there is an error');
return;
}
// If the process is ok, execute the callback without any parameter
callback();
}, function(err) {
// - Callback: this code will be executed when all iterator functions have finished or an error occurs
if(err)
console.log("show error");
else {
// Your code continues here...
}
});
This way your code is asynchronous (the iterator funcions are executed simultaneously) except the callback function that will be executed when all have finished.
The example with your code would be:
var elements = [1 .. n];
async.each(elements, function(element, callback) {
User.find( where { name: 'john'}, function(u) {
if(err)
{
callback(err);
return;
}
// Do things ...
callback();
});
}, function(err) {
if(err)
console.log("show error");
else {
// continue processing
}
});
All of those model methods (querying/updating data) are asynchronous. There are no synchronous versions. Instead, you'll need to use the callback function that you pass as the second argument:
for (var i = 0; i<n; ++i) {
User.find( {where: { name: 'john'} }, function(err, users) {
// check for errors first...
if (err) {
// handle the error somehow...
return;
}
// this is where you do any further processing...
// for example:
if (users[0].lastName === 'smith') { ... }
} );
}
async myFunction(){
for(var i = 0; i < n; i++) {
var u = await User.find( {where { name: 'john'}});
}
}