在$ http调用中使用then / catch
我的节点后端有以下端点:
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
的then block
我在我的控制器中使用我的服务,如下所示:
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; }); }
我的问题是,因为那个部分是在我的service
触发的。 我试图切片undefined
我的问题是:当涉及到这种模式时,什么是最佳实践?
问题在于,您从API捕获错误,然后返回由.catch
创build的承诺。
快速示例
promise.then(function(data) { throw 'Some error'; }).catch(function (err) { console.log(err) // will output 'Some error' }).then(function () { // This will run even though we have a catch before });
那么我们怎样才能防止.catch
的错误是很容易的
promise.then(function(data) { throw 'Some error'; }).catch(function (err) { console.log(err) // will output 'Some error' throw 'You shall not pass' }).then(function () { // This will not run });
所以在你的情况下,你有两个select,一个抛出一个错误,正如我所说的或两个注入$q
服务到您的服务:
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'); return $q.reject(err); } }
你可以做那样的事情
function getUsers(date, search, cb) { return $http.get('/api/users/get', { params: { date: UtilsService.formatDate(date), search: search } }) .then(cb) .catch(handleErr); function handleErr(err) { LoggerService.error('Could not retrieve users.', err ,'Ooops'); } }
然后在你的控制器
UsersService.getUsers(date, search, function(data) { vm.loading = false; allUsers = data || []; vm.filteredUsers = allUsers.slice(0, 50); vm.distribution = UsersService.getDistribution(allUsers); });