如何在严格模式下找到函数调用者

How to find function caller while in strict mode

本文关键字:函数 函数调用 调用者 模式      更新时间:2023-09-26

我有一个函数,getGames(),在我的Angular控制器中,可以由我的init()函数和update()函数调用。我需要知道init()update()是否调用了这个函数,因为我对每种情况都进行了不同的处理。

我试图访问arguments.callee.caller.toString(),但这是不允许的,而在严格模式下,这是这个项目的要求。

在严格模式下如何访问getGames()的调用者?

我的当前结构如下。显然updateSchedule()中的loadingGames.promise不起作用,因为当init()运行时,这个承诺已经解决了。我正在努力重构这一点,以便init()updateSchedule()各自依赖于关于同一函数getGames()的不同承诺分辨率。

var loadingGames = $q.defer();
var getGames = function() {
  playersService.getGames({
    playerId: playerId
  }).$promise.then(function(data) {
    vm.games = data;
    loadingGames.resolve();
  });
};
var init = function() {
  getGames();
}
init();
var updateSchedule = function() {
  getGames();
  loadingGames.promise.then(function() {
    populateOptions(vm.games);
    vm.tableParams.reload();
  });
};

我的想法是在getGames()结束时确定caller,然后根据调用者是谁来解决不同的承诺。

你的getGames() -函数可以返回一个承诺,这是解决一旦游戏已经从服务器(使我的示例代码更短,我省略了参数的服务,并假设它返回一个承诺):

var games; //This is vm.games in your case
(function fetchGames() {
    games = playersService.getGames()
        .then(function(data){
            games = data;
            return data;
        });
})();
function getGames() {
    return $q.when(games);
}
function updateSchedule() {
    getGames()
        .then(function(theGames){
            populateOptions(theGames);
            tableParams.reload();
        });
}

$q.when(x)返回一个承诺,如果x不是承诺,则立即与x解决。如果x是一个promise,它直接返回x

只是一个注意:你的populateOptionstableParam.reload函数看起来很像你做手工dom的东西。这在angular中几乎总是错误的——让数据绑定为你完成这项工作。