且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在不引发错误的情况下检查模块是否存在?

更新时间:2022-06-08 22:21:32

我不知道一种检查方法不会引发错误;但是,请注意问题在于它是 Uncaught Error,而不是抛出了错误.捕获此类错误的模式如下.

I am not aware of a way of checking without an error being raised; however, notice that the issue is that it was an Uncaught Error, not that an error was thrown. The pattern for catching such an error is the following.

try { angular.module("ngRoute") } catch(err) { /* failed to require */ }

如果发现错误,你可以尝试另一个模块,如果没有,你可以使用第一个.

If an error is caught, you can try the other module, and if not, you can use the first.

如果每个模块的行为都相同,则可以执行以下操作,其中我们定义了一个函数,该函数将尝试列出的模块名称中的第一个,如果抛出错误,则尝试下一个选项.

If your behavior will be the same for each module, you could do something like the following, in which we define a function which will attempt the first of the listed module names, and if an error is thrown, try the next option.

var tryModules = function(names) {
  // accepts a list of module names and
  // attempts to load them, in order.

  // if no options remain, throw an error.
  if( names.length == 0 ) {
    throw new Error("None of the modules could be loaded.");
  }

  // attempt to load the module into m
  var m;
  try {
    m = angular.module(names[0])
  } catch(err) {
    m = null;
  }

  // if it could not be loaded, try the rest of
  // the options. if it was, return it.
  if( m == null ) return tryModules(names.slice(1));
  else return m;
};

tryModules(["ngRoute", "ui.router"]);