[英]handle a function that returns a promise or a null value
我已经定义了一个函数如下:
function getCurrentComponent(){
if($rootRouter._currentInstruction){
return $rootRouter.recognize($rootRouter._currentInstruction.urlPath).then(function (data) {
return data.component.componentType;
});
}else{
return null;
}
}
要调用这个函数,我做了如下:
factory.getCurrentComponent().then(function (data) {
...
});
问题是当getCurrentComponent
函数返回空值时,会生成以下错误:
无法读取 null 的属性“then”
我该如何解决这个问题?
我忘了说我仅限于使用 ES5,所以我无法使用Promise
对象
使用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
});
如果您无法使用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.
...
});
我不能在 ES5 中使用对象Promise 。
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 通过提供自己的事件处理循环来修改正常的 JavaScript 流程。 这将 JavaScript 分为经典和 AngularJS 执行上下文。 只有在 AngularJS 执行上下文中应用的操作才会受益于 AngularJS 数据绑定、异常处理、属性监视等。
$q 服务是承诺/延迟对象的符合Promises/A+的实现,它与 AngularJS 框架及其摘要循环集成。
将函数转换为使用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);
})
}
现在您可以使用 then() 函数检查resolve
和reject
,
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.