gpt4 book ai didi

javascript - 当运行 block 中存在无限循环时,工厂中的 $http 成功回调不会运行

转载 作者:行者123 更新时间:2023-11-28 19:04:48 25 4
gpt4 key购买 nike

这是我的代码以及相关部分bolded :

authorization.js

 angular      .module('mean-starter')      .run(run);    function run($rootScope, Auth, $state) {      $rootScope.$on('$stateChangeStart', function(event, toState, toParams) {        if (typeof toState.authenticate !== 'undefined') {          var currentUser = Auth.getCurrentUser();          while (!currentUser._id) {}          var isAdmin = currentUser.role === 'admin';          var isAuthorized = currentUser._id.toString() === toParams.id;          if (!Auth.isLoggedIn()) {            event.preventDefault();            alert('Must be logged in to access this route.');            $state.go('login');          }          else if (toState.authenticate.authorized) {            if (!isAdmin && !isAuthorized) {              event.preventDefault();              alert('You are not authorized to access that route.');            }          }          else if (toState.authenticate.isAdmin) {            if (!isAdmin) {              event.preventDefault();              alert('You must be an admin to access this route.');            }          }        }      });    }

auth.factory.js

angular  .module('mean-starter')  .factory('Auth', function($http, $state, $window, $cookies) {    console.log('factory cb');    var currentUser = {};    if ($cookies.get('userId')) {      console.log('userId');      $http        .get('/current-user')        .success(function(data) {          console.log('success');          angular.copy(data, currentUser);        })        .error(function() {          console.log('Problem getting the current user.');        });    }    return {      signup: function(user) {        return $http.post('/users', user)                  .success(function(data, status, headers, config) {                    angular.copy(data, currentUser);                    $cookies.put('userId', data._id);                    $window.location.href = '/';                  });      },      login: function(user) {        return $http                  .post('/login', user)                  .success(function(data) {                    angular.copy(data, currentUser);                    $cookies.put('userId', data._id);                    $window.location.href = '/';                  });      },      logout: function() {        $http          .get('/logout')          .success(function() {            angular.copy({}, currentUser);            $cookies.remove('userId');            $window.location.href = '/';          })          .error(function() {            console.log('Problem logging out.');          });      },      getCurrentUser: function() {        return currentUser;      },      isLoggedIn: function() {        return !!currentUser._id;      }    };  });

My problem is that without the while loop, I get this error:

Cannot read property 'toString' of undefined

它指的是currentUser._id未定义并且我试图对其调用toString。我的理解是 Auth.getCurrentUser() 最初返回对 {} 的引用。然后,赋值语句将 {} 分配给 currentUser,代码继续执行。当响应返回时,它应该更新 {},因此应该“更新”currentUser,因为 currentUser 指向更新的对象。

如果这是真的,我的问题就可以理解了,因为它试图在响应返回之前执行 currentUser._id.toString() 。因此,我尝试做的是将 while 循环放在那里,以基本上暂停执行,直到响应返回。但是 while 循环无限运行!如果响应最终不返回,请更新 currentUser,当返回时,!currentUser._id 应该为 false,并且循环应该打破?

第一个factory cb已注销。然后userId被注销。到目前为止,一切都很好。但随后无限循环开始,成功永远不会被注销。请求不是应该是异步的吗? while 循环怎么能阻止它呢?这是怎么回事?

通话没有问题。如果没有 while 循环,它会触发成功回调并记录success。此外,如果我在 authorization.jsconsole.dir(currentUser) 它会给我用户,但如果我 console.log(currentUser) ,它给了我一个空对象。不知道为什么会这样。

最佳答案

据我所知,由于 Javascript 是单线程的,当线程在 while 循环中旋转时,http 回调将不会获得 CPU 时间来处理响应。

关于javascript - 当运行 block 中存在无限循环时,工厂中的 $http 成功回调不会运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31900999/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com