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);
我正在尝试返回响应数据并将其存储到最终变量中,而不是获取 promise 对象。
如何返回实际数据?
最佳答案
我将尝试根据您的代码开发 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);
执行顺序如下:
最终变量
$http.get('http://localhost:9000/therapist_data',config) .success();
:当服务器响应您的请求时,这将触发请求并成功注册该函数作为回调console.log(final);
-> 所以仍然未定义。它不等待响应。- 一段时间后...调用成功时的函数。
这是回调和异步处理的基础,你不知道它什么时候执行,或者至少,它经常在所有其他代码之后执行。在 angularJS 中,没有办法进行同步请求。您必须在成功函数中移动您的代码。
关于javascript - 如何使 $http.get 返回响应而不是 promise 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37294842/