【问题标题】:How to make $http.get return response instead of promise object?如何使 $http.get 返回响应而不是 promise 对象?
【发布时间】:2016-05-18 09:01:18
【问题描述】:
var final;
final = $http.get('http://localhost:9000/therapist_data',config)
             .success(function(response) {
            console.log("I got the data I requested");
            var resdata = response;
            console.log(resdata);
            return resdata;
        });

console.log(final);

我正在尝试返回响应数据并将其存储到最终变量中,而不是获取承诺对象。
如何返回实际数据?

【问题讨论】:

  • 您可能想要创建自己的自定义服务。

标签: javascript angularjs http asynchronous get


【解决方案1】:

我将尝试根据您的代码开发 Cyril 答案:

var final;
final = $http.get('http://localhost:9000/therapist_data',config)
         .success(function(response) {
        console.log("I got the data I requested");
        var resdata = response;
        console.log(resdata);
        return resdata;
    });

console.log(final);

执行顺序如下:

  1. var final
  2. $http.get('http://localhost:9000/therapist_data',config) .success(); : 当服务器响应你的请求时,这将触发请求并成功注册函数作为回调
  3. console.log(final); -> 所以仍然未定义。它不会等待响应。
  4. 有些时候...你的函数在成功中被调用。

这是回调和异步处理的基础,你不知道它什么时候执行,或者至少,它通常会在所有其他代码之后执行。在 angularJS 中,没有办法进行同步请求。您必须在成功函数中移动代码。

【讨论】:

  • 全部正确,执行顺序非常好,+1!
【解决方案2】:

只要你在进行网络调用,你的数据就会异步返回,这是它的本质,你无法抗拒它。

var wrongFinal; // <-- nope, final will never get into that scope
$http.get('http://localhost:9000/therapist_data',config)
     .success(function(response) {
     console.log("I got the data I requested");
     var goodFinal = reponse; // <-- yes, here, the data lived
     // do something with the data here
});

console.log(wrongFinal); // nop, wrong scope, no sense, data doesn't live here

Soooooo,答案是一个问题:

你想用你的数据做什么?

这取决于目的地。你要打另一个网络电话吗?是否要更新视图?是否要调用第 3 方库?

您需要了解并接受 JavaScript 中异步的本质。

【讨论】:

  • 是的,实际上上面的代码在另一个http get的另一个成功函数中。它的嵌套网络调用。
【解决方案3】:

$http.get 将始终返回一个承诺。
如果您想获得承诺值,您应该在 success 回调中进行,如下所示:

var final;
$http.get('someUrl').success(function(response) {
final = response;
}); 

不需要 resData,只会导致一个承诺链,在这种情况下你不需要。

【讨论】:

  • 试过了,但是当我成功定义 final 时,它的作用域只限于本地成功函数。即外部 final 变量仍然未定义。
  • 你在调试的时候,有没有点击成功功能?也许承诺被拒绝了,final 没有改变。
  • 在某些情况下,我声明了一个组件属性,然后在构造函数中调用了一个异步函数。在返回承诺后,我填充了属性(使用then)。我不清楚为什么 final 变量不在范围内。@Cyril Gandon?
猜你喜欢
  • 1970-01-01
  • 2021-05-18
  • 1970-01-01
  • 1970-01-01
  • 2020-11-28
  • 2018-11-03
  • 2015-02-27
  • 2021-04-28
  • 1970-01-01
相关资源
最近更新 更多