处理返回 Promise 或 null 值的函数

Ich*_*aki 3 javascript ecmascript-5 angularjs angular-promise

我定义了一个函数如下:

function getCurrentComponent(){
    if($rootRouter._currentInstruction){
        return $rootRouter.recognize($rootRouter._currentInstruction.urlPath).then(function (data) {
            return data.component.componentType;
        });
    }else{
        return null;
    }
}
Run Code Online (Sandbox Code Playgroud)

为了调用这个函数,我做了如下操作:

factory.getCurrentComponent().then(function (data) {
    ...
});
Run Code Online (Sandbox Code Playgroud)

问题是当getCurrentComponent函数返回空值时,会生成以下错误:

无法读取 null 的属性“then”

我该如何解决这个问题?

编辑:

我忘了说我仅限于使用 ES5,所以我无法使用该对象Promise

Ele*_*Ele 7

使用Promise.reject()功能。

function getCurrentComponent() {
  if ($rootRouter._currentInstruction) {
    return $rootRouter.recognize($rootRouter._currentInstruction.urlPath).then(function(data) {
      return data.component.componentType;
    });
  } else {
    return Promise.reject('_currentInstruction is fale');
  }
}

factory.getCurrentComponent().then(function(data) {
  ...
}).catch(function(e) {
  console.log(e); // Output: _currentInstruction is fale
});
Run Code Online (Sandbox Code Playgroud)

资源


如果您无法使用,Promise您可以返回一个带有函数的对象then

function getCurrentComponent() {
  if ($rootRouter._currentInstruction) {
    return $rootRouter.recognize($rootRouter._currentInstruction.urlPath).then(function(data) {
      return data.component.componentType;
    });
  } else {
    var helperThen = { then: function(fn) { fn(null) } };
    return helperThen;
  }
}

factory.getCurrentComponent().then(function(data) {
  // Check if data is null.
  ...
});
Run Code Online (Sandbox Code Playgroud)