Carmen
Carmen

Reputation: 45

Sails js -model resultset variable scope

Can someone explain to me why i can't save the booksCount variable into the users json object? Here's my code

for(var user in users){
    Books.count({author: users[user]['id']}).exec(function(err, count){
        users[user]['booksCount']=count;
        });
    }
return res.view('sellers', {data: users});

Where Users is the list of users from the table which is the direct result of a User.find() method. User is the model.

Now if i try to print the users[user]['booksCount'] inside the for loop, it works fine. But when it goes outside the for loop the variable vanishes into thin air. Console prints 'undefined' outside for loop.

Upvotes: 2

Views: 157

Answers (1)

Vishnu Mishra
Vishnu Mishra

Reputation: 4029

Because Books.count is an API call and all the API call are async so In

for(var user in users){
    // It Will call the Books.count and leave the callback Function without waiting for callback response.
    Books.count({author: users[user]['id']}).exec(function(err, count){ 
       users[user]['booksCount']=count;
    });
}
//As callback result didn't came here but the controll came here
// So, users[user] will be undefined here
return res.view('sellers', {data: users});

Use promises:

async.forEachOf(users, function (value, user, callback) {
    Books.count({author: users[user]['id']}).exec(function(err, count){ 
           users[user]['booksCount']=count;
           callback(err);
         // callback function execute after getting the API result only
        });
}, function (err) {
    if (err) return res.serverError(err.message); // Or Error view
    // You will find the data into the users[user]
    return res.view('sellers', {data: users});
});

Upvotes: 1

Related Questions