我有一个自定义函数,可正确返回用户详细信息的缓存对象。此外,该函数会事先检查缓存是否为空,并在必要时进行API调用以检索适当的数据。但是,当我从角度ui-router解析时调用此函数时,它仍然会变得未定义。我不明白...因为自定义函数中的所有控制台打印语句都显示正在返回正确的对象。
function getCache(UserService) {
if(cacheIsEmpty) {
UserService.getProfile().then(function (profile) {
// check to see profile returned correctly
console.dir(profile);
// set cache using returned profile
...
// create object loaded from cache
var cacheObj = {
firstName: // get from cache
lastName: // get from cache
...
}
// check if my object is correctly created
console.log(cacheObj):
// now return this correctly created object
return cacheObj;
});
} else {
// the following creates object directly from cache
// since it is NOT empty and can be used
var cacheObj = {
firstName: // get from cache
lastName: // get from cache
...
}
// print to check object is correct
console.dir(cacheObj);
// now return it
return cacheObj;
}
}
在解决方案中,对该函数的调用将按照定义返回...尽管该对象正确地从对象返回。
...
resolve: {
cacheObj: function(UserService) {
// call the getCache function
var returnedUserObject = getCache(UserService);
// printing the object here shows that it is undefined
console.log(returnedUserObject);
// return the object to the controller
return returnedUserObject;
}
}
答案 0 :(得分:0)
您应该从var id =[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20];
函数返回一个承诺,以便getCache
认识到,直到承诺得到解决,我需要等待。在这里,您尚未通过resolve
方法返回承诺,您正在进行if(cacheIsEmpty)
方法调用。虽然从UserService.getProfile
函数的承诺中返回数据并不意味着您将返回承诺。
<强>代码强>
.then
<强>解析强>
function getCache(UserService) {
//return promise from both the places, if & else
if(cacheIsEmpty) {
//return promise here
return UserService.getProfile().then(function (profile) {
// check to see profile returned correctly
console.dir(profile);
// set cache using returned profile
...
// create object loaded from cache
var cacheObj = {
firstName: // get from cache
lastName: // get from cache
...
}
//return cacheObj from here when promise resolved
return cacheObj;
});
} else {
//create cached cacheObj from cache and return it
return $q.resolve(cacheObj)
}
}