6

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

Raj Lalwani
  • 391
  • 1
  • 6
  • 14

3 Answers3

2

You 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
    }

});
gyss
  • 1,753
  • 4
  • 23
  • 31
1

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') { ... }
    } );
}
Jordan Kasper
  • 13,153
  • 3
  • 36
  • 55
0
async myFunction(){
  for(var i = 0; i < n; i++) {
    var u = await User.find( {where { name: 'john'}});
  }
}
kz_sergey
  • 677
  • 5
  • 19