gpt4 book ai didi

javascript - 我应该模拟 '.$promise' 对象吗?

转载 作者:行者123 更新时间:2023-12-03 12:09:48 25 4
gpt4 key购买 nike

我正在使用 AngularJS 开发一个管理应用程序。应用程序使用 $resource 从服务器获取数据。我最终得到包含“$promise”属性的数据对象来确定何时获取数据。一切都很好。

现在,这个管理应用程序还可以创建新对象。这些新对象由与通常来自“$resource”的 Controller 相同的 Controller 管理。

所以现在我有两种对象:

  • 具有 $promise 属性的对象。在使用完整数据操作它们之前,我应该使用 $promise.then()
  • 普通物体。它们没有 $promise 属性,它们的值可以立即访问

我想减少代码并拥有单一用例,而不必检查对象数据是否已解析,或者是否不是 promise 。

通过添加已经解析为自身的“$promise”属性来构建“普通”对象是否有任何问题?这样,我将始终使用“myObject.$promise.then()”。

有没有通用的模式来处理这种情况?我找不到任何“标准”方法来使用 Angular 创建此类对象。

最佳答案

您可以使用$q.when如果不确定该对象是否有 promise 。

(obj.$promise ? obj.$promise || $q.when(objResult)).then(function(result){
//handle success case.
//Incase of object not having the $promise property result will be object itself
})

如果生成的属性没有 promise ,则将通过 promise 解决。

Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise. This is useful when you are dealing with an object that might or might not be a promise, or if the promise comes from a source that can't be trusted.

您不需要总是创建 promise 并将其附加到正在传输的数据上,相反,您可以使您的方法返回 promise ,从而帮助您实现 promise 模式并抽象出服务本身的 promise 逻辑。示例:-

   function getCurrentUserData(userId){
var defered = $q.defer();
...
//Check in my cache if this is already there, then get it from cache and resolve it
defered.resolve(objectFromCache);
//my else condition
//It is not in cache so let me make the call.
$http.get('myurl').then(function(result){
//Do validation with data and if it doesnot match then reject it
defered.reject(reason);
//Else Do something with the data put it into the cache, mapping logic etc..
defered.resolve(dto);


}).catch(function(error){
//do something with error and then reject
defered.reject(reasonDerived);
});
return defered.promise;
}

这是一个简化且不太明确的版本(来源:Benjamin Gruenbaum):

var cached = null;
function getCurrentUserData(userId){
return cached = cached || $http.get('myurl').then(function(result){
if(isNotValid(result)) return $q.reject(reason); // alternatively `throw`
return transformToDto(result);
}, function(response){
if(checkforsomethingonstatusandreject)
return $q.reject('Errored Out')
//do some actions to notify the error scenarios and return default actions
return someDefaults; });
}

您当然可以在这里返回$q.reject(衍生原因),而不是返回原因并根据进一步检查对其进行转换,这个想法是缓存 promise 而不是值。这还有一个优点,如果在返回一次之前调用该方法,则不会发出多个 http 请求。

现在你总是可以这样做:-

    getCurrentUserData(userid).then(function(user){

}).catch(function(error){

});

Promise 也可以被链接起来。所以你也可以这样做:-

   return $resource('myresource').$promise.then(function(result){
//Do some mapping and return mapped data
return mappedResult;
});

关于javascript - 我应该模拟 '.$promise' 对象吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25006532/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com