Sails JS: how to return a value from a service

I create a service in js sails. I want to update the value of totalCount before returning it. But the problem is that returning in the async.series callback I get undefined when I call it. How can I do it?

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; }); 
+6
source share
1 answer

I'm not quite sure what you are trying to do. But you probably want to pass totalCount in the 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 forward with an error as the first parameter, so do a null check. If the first parameter is NULL, then the second parameter will be the length of your array.

If you prefer to return all products, and not just length (as the name of the function implies), then this is 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 would use this in 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... } 
+7
source

Source: https://habr.com/ru/post/984059/


All Articles