2015-09-07 28 views
2

我试图从函数获取count值,并且想要存储在函数的外部。sails:如何获得函数外的值

var count;  
client.count({ 
       index: 'employee', 
       type: 'details', 
      }, function (err, response) { 
        if(err){console.log(err)} 
        count = response.count 
        console.log(count); 
    }); 

console.log(count); 我想在该功能之外使用此计数。 这可能吗?

+0

你从找出一个复制粘贴了。这会起作用,但不推荐。理想情况下,您应该使用回调函数返回所有值。 – galactocalypse

+0

我已经搜索过关于这个问题,但可以找到。 – Martin

+0

没有它不适合我。 – Martin

回答

3

试着写你的代码是这样的:

client.count({ 
       index: 'employee', 
       type: 'details', 
      }, afterCount); 
function afterCount(err, count){ 
    if (err) console.log(err); 
    // do whatever you want with count 
    // if there's too much logic, split it into functions and send count as a param to them 
} 
+1

好的谢谢你的帮助 – Martin

2

包装在一个函数中或使用Promise API来重构您的代码。

function(cb){ 
    var count; 
    ...... 
    cb(count); 
}