我正在实现一个“写入时复制”CRUD系统,这意味着我从不覆盖数据库条目,但标记为非活动状态并写入新记录。编辑现有记录时,这意味着我写入旧记录停用,然后创建新记录。我的控制器代码如下:
$scope.save = function() {
if(!$scope.newDevice){
var editDevice = $scope.device;
$scope.delete(editDevice);
$scope.device = {name: editDevice.name, type: editDevice.type, hash: editDevice.hash};
}
var newDevice = new DeviceService($scope.device);
newDevice = newDevice.$save(function(newDevice, putResponseHeaders) {
DeviceService.query({active : true}, function(devices){
$scope.devices = devices;
});
});
};
当我打电话来获取带有DeviceService.query的活动设备列表时({active:true}我仍然将旧记录视为活动,因为它执行并在处理并返回delete方法之前返回。
我想我应该使用诺言。我如何编写此代码以更好地工作?
感谢
答案 0 :(得分:0)
是的,你想使用promises。您有两种选择:
使用所有$ resource方法提供的成功/失败回调。请注意,当您拨打$ save时,您正在使用此功能。当你在资源上调用$ delete时,你也可以这样做,这样你的剩余代码只有在$ delete()成功时才会执行。当$ resource的内置承诺被解决或拒绝时,会自动调用这些回调。
让您的$scope.delete()
函数返回一个承诺。听起来这可能会更好,因为您并不总是想要删除请求。
#2的代码可能如下所示:
// this function use the '$q' service, which you need to inject
// in your controller
$scope.delete = function(item) {
var deferred = $q.defer();
item.$delete({},
function(response) {
// the delete succeeded, resolve the promise
deferred.resolve(response);
},
function(error) {
// failed, reject the promise
deferred.reject(error);
}
);
return deferred.promise;
}
$scope.save = function() {
if(!$scope.newDevice){
var editDevice = $scope.device;
$scope.delete(editDevice).then(function(response) {
$scope.device = {name: editDevice.name, type: editDevice.type, hash: editDevice.hash};
// now trigger the code to save the new device (or whatever)
$scope.doTheActualSave();
},
function(error) { });
} else {
// there was nothing to delete, just trigger the code to save
$scope.doTheActualSave();
}
};
$scope.doTheActualSave = function() {
var newDevice = new DeviceService($scope.device);
newDevice = newDevice.$save(function(newDevice, putResponseHeaders) {
DeviceService.query({active : true}, function(devices){
$scope.devices = devices;
});
});
}