简体   繁体   English

处理返回承诺或空值的函数

[英]handle a function that returns a promise or a null value

I have defined a function as following :我已经定义了一个函数如下:

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

To call this function I did as following :要调用这个函数,我做了如下:

factory.getCurrentComponent().then(function (data) {
    ...
});

The problem is when the getCurrentComponent function returns a null value, the following error is generated :问题是当getCurrentComponent函数返回空值时,会生成以下错误:

Cannot read property 'then' of null无法读取 null 的属性“then”

How can I solve this ?我该如何解决这个问题?

Edit:编辑:

I forgot to say that I'm limited to use ES5, so I can't work with the object Promise我忘了说我仅限于使用 ES5,所以我无法使用Promise对象

Use Promise.reject() function.使用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
});

Resource资源


If you're unable to use Promise you can return an object with a function then .如果您无法使用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.
  ...
});

I cant use the object Promise in ES5.我不能在 ES5 中使用对象Promise

Use the AngularJS $q Service :使用AngularJS $q 服务

function getCurrentComponent(){
    if($rootRouter._currentInstruction){
        return $rootRouter.recognize($rootRouter._currentInstruction.urlPath).then(function (data) {
            return data.component.componentType;
        });
    }else{
        ̶r̶e̶t̶u̶r̶n̶ ̶n̶u̶l̶l̶;̶
        return $q.reject(null);
    }
}

AngularJS modifies the normal JavaScript flow by providing its own event processing loop. AngularJS 通过提供自己的事件处理循环来修改正常的 JavaScript 流程。 This splits the JavaScript into classical and AngularJS execution context.这将 JavaScript 分为经典和 AngularJS 执行上下文。 Only operations which are applied in the AngularJS execution context will benefit from AngularJS data-binding, exception handling, property watching, etc.只有在 AngularJS 执行上下文中应用的操作才会受益于 AngularJS 数据绑定、异常处理、属性监视等。

The $q Service is a Promises/A+ -compliant implementation of promises/deferred objects thst is integrated with the AngularJS framework and its digest cycle. $q 服务是承诺/延迟对象的符合Promises/A+的实现,它与 AngularJS 框架及其摘要循环集成。

Convert the function to use a Promise .将函数转换为使用Promise

function getCurrentComponent(){
    return new Promise((resolve, reject)=>{
      if($rootRouter._currentInstruction){
          resolve( $rootRouter.recognize($rootRouter._currentInstruction.urlPath).then(function (data) {
              return data.component.componentType;
          }));
    } else{
        reject(null);
    })
}

Now you can check resolve and reject with then() function,现在您可以使用 then() 函数检查resolvereject

factory.getCurrentComponent().then(function (resolved) {
    //handle success here
}, function(rejected) {
   // handle rejection here
});

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM