【发布时间】:2016-10-01 21:53:01
【问题描述】:
我的 Node 后端有以下端点:
usersRoute.get('/get', function(req, res) {
//If no date was passed in - just use todays date
var date = req.query.date || dateFormat(new Date(), 'yyyy-mm-dd'),
search = req.query.search;
users.getAllUsers(date, search)
.then(function(results) {
res.json(results);
}, function(err) {
res.status(500).json({
success: false,
message: 'Server error.',
data: []
});
});
});
我已将我的 sql 表名更改为其他名称以触发 function(err){} 部分
当我在我的服务中使用它时,它看起来像这样:
function getUsers(date, search) {
return $http.get('/api/users/get', {
params: {
date: UtilsService.formatDate(date),
search: search
}
})
.then(getData)
.catch(handleErr);
function getData(response) {
return response.data;
}
function handleErr(err) {
LoggerService.error('Could not retrieve users.', err ,'Ooops');
}
}
知道服务器将返回http status code 500,我认为它会直接返回catch block。但它也返回数据/这是then block中的undefined
我在控制器中这样使用我的服务:
function getUsers(date, search) {
isAdmin();
vm.loading = true;
vm.filteredUsers = [];
return UsersService.getUsers(date, search).then(function(data) {
vm.loading = false;
allUsers = data || [];
vm.filteredUsers = allUsers.slice(0, 50);
vm.distribution = UsersService.getDistribution(allUsers);
return vm.filteredUsers;
});
}
我的问题是,因为then 部分是在我的service 中触发的。我正在尝试切片undefined
我的问题是:对于这种模式,有哪些最佳实践。
【问题讨论】:
-
您确定您的服务器响应为 500?因为那肯定会触发捕获。
-
@FabioAntunes 我会稍微编辑一下我的问题。 catch 被触发,但也触发了“then 部分”。
-
现在我明白了,我有适合你的解决方案
标签: javascript angularjs node.js http asynchronous