2015-09-07 71 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); 
}