JavaScript 变量使用外部函数

javascript variable use outside function

本文关键字:外部 函数 变量 JavaScript      更新时间:2023-09-26
$scope.pagination_data = function(page_data){
   count = page_data.data.count;
};
console.log("outside count is",count);// this not working
var page = function(){
 userService.paginate()
  .then(function(user){
    $scope.pagination_data(user);
    console.log("count is",count);//this is works
  });
};

在该代码中,我正在使用$http服务,我正在获取数据AFTR,我想要一个计数,然后我也得到计数,但现在我希望在控制器中访问这个计数变量,但这对我来说无法访问。 我该怎么办..?

实际上,两者都有效,但您在错误的时间调用了第一个。

.then()表示paginate()返回一个承诺。这应该暗示它是异步的。

为了证明这一点,请使用setTimeout延迟调用您的第一个控制台.log

$scope.pagination_data = function(page_data){
   count = page_data.data.count;
};
setTimeout(function(){
    console.log("outside count is",count);// this should work
}, 5000); // wait 5 seconds before calling the code above
// If 5 seconds is not long enough increase it to 10 or something
var page = function(){
 userService.paginate()
  .then(function(user){
    $scope.pagination_data(user);
    console.log("count is",count);//this is works
  });
};

什么是异步代码?异步只是意味着稍后将调用代码。paginate().then()所做的不是立即调用function(user)函数,而是记住它应该在以后调用function(user)(然后调用您的pagination_data函数来设置count的值(。然后它继续运行其他东西。

当没有其他代码要运行时,将处理事件循环,并且userService.paginate()需要异步执行的任何操作都将得到处理。

userService.paginate()等待的任何内容最终返回(这可能是网络请求、用户单击等(时,最终调用function(user)函数。这反过来又调用$scope.pagination_data() 这是将结果分配给全局count变量的原因。

setTimeout()做什么?好吧,它的作用与我上面描述的相同。它不会立即呼叫console.log(),而是记得稍后呼叫它。然后,当 5 秒(5000 毫秒(到期,并且没有其他 JavaScript 代码正在运行(这很重要,因为这意味着 javascript 可以运行事件循环(时,最终调用console.log()

只需在外面定义变量即可。

var count = 0;
$scope.pagination_data = function(page_data){
   count = page_data.data.count;
};
console.log("outside count is",count);// this not working
var page = function(){
 userService.paginate()
  .then(function(user){
    $scope.pagination_data(user);
    console.log("count is",count);//this is works
  });
};

fist 语句只定义函数,不调用它。如果有数据要传递给该函数,请在记录计数之前调用它。

   // this only defines the function, doesn't call it
    $scope.pagination_data = function(page_data){
       count = page_data.data.count;
    };
    console.log("outside count is",count);// count is still unset
    var page = function(){
     userService.paginate()
      .then(function(user){
        $scope.pagination_data(user); // this is the call, count will be set
        console.log("count is",count);//this will work
      });
    };