angularjs上下文中的以下代码中的$ q.defer()有什么作用 [英] What does $q.defer() in following code in angularjs context

查看:45
本文介绍了angularjs上下文中的以下代码中的$ q.defer()有什么作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码中$ q.defer()的用途是什么.我有点困惑或无法理解$ q的使用还是推迟?

  service.serviceCall =函数(methodName,参数){var deferred = $ q.defer();$ http({method:"POST",url:url + methodName,data:params,headers:headers}).success(function(result){deferred.resolve(result);}).error(函数(结果){deferred.reject(result);});返回deferred.promise;} 

解决方案

代码在调用 $ http 的结果上使用了不赞成使用的方法.尽管 $ http 返回了一个承诺,但是它还有一些其他方法 .success .error ,它们在常规的promise结构中不太起作用./p>

$ q.defer()创建一个从函数返回的承诺,该代码使用成功 error 来解决承诺.编写此代码的一种更简单的方法是仅使用 $ http 及其它的 .then 方法返回的promise.

  service.serviceCall =函数(methodName,参数){返回$ http({方法:"POST",URL:url + methodName,数据:params,标头:headers}).then(函数successFn(response){返回response.data;});} 

这与原始代码具有相同的效果:它返回一个承诺,该承诺将解析响应中的数据,或者如果发生错误,则承诺将被拒绝.

What is the use of $q.defer() in following code. I am bit confused or not able to understand the use of $q or defer?

  service.serviceCall = function (methodName, params) {
    var deferred = $q.defer();
    $http({ method: "POST", url: url + methodName, data: params, headers: headers }).success(function (result) {
        deferred.resolve(result);
    }).error(function (result) {
        deferred.reject(result);
    });
    return deferred.promise;
}

解决方案

The code is using deprecated methods on the result of calling $http. Although $http returns a promise it has some additional methods .success and .error that don't quite work within the usual promise structure.

$q.defer() creates a promise which is returned from the function and this code uses success and error to resolve the promise. A simpler way to write this code would be to just use the promises returned by $http and its .then method.

  service.serviceCall = function (methodName, params) {
    return $http({ method: "POST", url: url + methodName, data: params, headers: headers })
    .then(function successFn (response) {
        return response.data;
    });
}

This has the same effect as the original code: it returns a promise which either resolves to the data from the response, or if an error occurs the promise is rejected.

这篇关于angularjs上下文中的以下代码中的$ q.defer()有什么作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆