Javascript sails:如何获取函数外部的值
我试图从函数中获取Javascript sails:如何获取函数外部的值,javascript,node.js,sails.js,waterline,Javascript,Node.js,Sails.js,Waterline,我试图从函数中获取count值,并希望存储在函数外部 var count; client.count({ index: 'employee', type: 'details', }, function (err, response) { if(err){console.log(err)} count = respons
count
值,并希望存储在函数外部
var count;
client.count({
index: 'employee',
type: 'details',
}, function (err, response) {
if(err){console.log(err)}
count = response.count
console.log(count);
});
控制台日志(计数);
我想在函数之外使用此计数。
这可能吗?封装在函数中或使用Promise API重构代码
function(cb){
var count;
......
cb(count);
}
尝试以这种方式编写代码:
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
}
你很难找到答案。这将起作用,但不推荐使用。理想情况下,您应该使用回调返回所有值。我已经搜索了有关此问题的信息,但找不到。不,这对我不起作用。您可以共享“it”吗?您正在尝试的代码片段?我已经将其与我的问题共享了。