帆:如何获取函数外部的值

sails: how to get a value outside of the function

本文关键字:函数 外部 获取 何获取      更新时间:2023-09-26

我试图从函数中获得count值,并希望存储在函数外部。

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

console.log(数);我想在函数外使用这个计数。这可能吗?

试着这样写代码:

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
}

在函数中包装或者使用Promise API来重构你的代码。

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