Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sails JS : How to return a value from a service

I am creating a service in sails js. I want to update the value of totalCount before returning it. But the problem is when the return is in the callback of the async.series I am getting an undefined when I'm invoking it. How should I do this?

var totalCount = 0;

    async.series([
        function getProducts(cb_series){
            Inventory.find({sku_id : sku_id, bay_id : bay_id})
                .then(function(inventory_items){

                    async.each(inventory_items, function(item, cb_each){
                        totalCount = totalCount + item.physical_count;
                        cb_each();
                    }, function(err){
                        if(err)
                            console.log(err);

                        cb_series();
                    });             
                });
        }
    ], function returnResult(err, cb){
        if(err)
            console.log(err);

        return totalCount;
    });
like image 674
Emmanuel Campos Avatar asked Mar 20 '15 17:03

Emmanuel Campos


1 Answers

I'm not totally sure what you're trying to do. But you probably want to pass totalCount out in a callback like this:

function getProducts(callback){
    Inventory.find({sku_id : sku_id, bay_id : bay_id}).then(
        function(inventory_items){
            callback(null, inventory_items.length)
        }, function(err){
            console.log(err);
            callback(err);
        });
}

If there is an error, it will call back with the error as it's first parameter, so do a null check on that. If the first parameter is null, then the second parameter will be the length of your array.

If you'd rather return all of the products and not just the length (as the name of the function implies), then it's very similar:

function getProducts(callback){
    Inventory.find({sku_id : sku_id, bay_id : bay_id}).then(
        function(inventory_items){
            callback(null, inventory_items)
        }, function(err){
            console.log(err);
            callback(err);
        });
}

You'd use it like this for the first case:

getProducts(function(err, productCount) {
    if(err) {
        console.log(err);
        return err;
    } else {
        var totalCount = productCount;
    }
    //etc etc...
}

...or this for the second case:

getProducts(function(err,products) {
    if(err) {
        console.log(err);
        return err;
    } else {
        var productArray = products;
    }
    //etc etc...
}
like image 88
Daniel Patrick Avatar answered Oct 13 '22 07:10

Daniel Patrick