如何在成功处理程序之外使用$ http Promise响应 [英] How to use $http promise response outside success handler

查看:106
本文介绍了如何在成功处理程序之外使用$ http Promise响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

$scope.tempObject = {};

 $http({
   method: 'GET',
   url: '/myRestUrl'
}).then(function successCallback(response) {
   $scope.tempObject = response
   console.log("Temp Object in successCallback ", $scope.tempObject);
}, function errorCallback(response) {

});
console.log("Temp Object outside $http ", $scope.tempObject);

我在successCallback中得到响应,但是 没有将$scope.tempObject移到$http之外.其显示为undefined.

I am getting response in successCallback but not getting $scope.tempObject outside $http. its showing undefined.

$http

推荐答案

但是如果我想在回调后使用$ scope.tempObject,那么我该如何使用它. ?

But if I want to use $scope.tempObject after callback so how can I use it. ?

您需要从httpPromise中链接.保存httpPromise并将值返回到onFullfilled处理函数.

You need to chain from the httpPromise. Save the httpPromise and return the value to the onFullfilled handler function.

//save httpPromise for chaining
var httpPromise = $http({
   method: 'GET',
   url: '/myRestUrl'
}).then(function onFulfilledHandler(response) {

   $scope.tempObject = response

   console.log("Temp Object in successCallback ", $scope.tempObject);

   //return object for chaining
   return $scope.tempObject;

});

然后从httpPromise 之外进行.

Then outside you chain from the httpPromise.

httpPromise.then (function (tempObject) {
    console.log("Temp Object outside $http ", tempObject);
});

有关更多信息,请参见 AngularJS $ q服务API参考- -链接诺言.

For more information, see AngularJS $q Service API Reference -- chaining promises.

可以创建任意长度的链,并且由于一个承诺可以用另一个承诺来解决(这将进一步推迟其解决方案),因此可以在链中的任何点暂停/推迟对承诺的解决.这样就可以实现功能强大的API. 1

It is possible to create chains of any length and since a promise can be resolved with another promise (which will defer its resolution further), it is possible to pause/defer resolution of the promises at any point in the chain. This makes it possible to implement powerful APIs.1

console.log("Part1");
console.log("Part2");
var promise = $http.get(url);
promise.then(function successHandler(response){
    console.log("Part3");
});
console.log("Part4");

"Part4"的控制台日志不必等待数据从服务器返回. XHR 启动后立即执行. "Part3"的控制台日志位于成功处理程序函数内部,该函数由

The console log for "Part4" doesn't have to wait for the data to come back from the server. It executes immediately after the XHR starts. The console log for "Part3" is inside a success handler function that is held by the $q service and invoked after data has arrived from the server and the XHR completes.

console.log("Part 1");
console.log("Part 2");
var promise = new Promise(r=>r());
promise.then(function() {
    console.log("Part 3");
});
console.log("Part *4*");

什么是显式的Promise构建反模式?如何避免?

如何是javascript异步且是单线程的吗?

忍者小队-陷阱,反模式以及有关AngularJS的提示
好的理论,但需要更新以使用.then.catch方法.

您错过了承诺的内容

这篇关于如何在成功处理程序之外使用$ http Promise响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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