Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call model.find method synchronously in node / loopback?

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

like image 634
Raj Lalwani Avatar asked Jan 27 '15 14:01

Raj Lalwani


2 Answers

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
    }

});
like image 89
gyss Avatar answered Oct 06 '22 01:10

gyss


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') { ... }
    } );
}
like image 21
Jordan Kasper Avatar answered Oct 06 '22 00:10

Jordan Kasper