Return 来自 http 内部函数的数据

Return data from http inside function

我正在使用 this and this 引用,从函数内部的 http 请求 return 数据:

function getdetails(id) {

            var datafordetails = {
                data1: {
                    item1: "",
                    item2: ""
                },
                data2: {
                    item3: "",
                    ID: id
                }
            };

            var jsonDataDetails = JSON.stringify(datafordetails);
            return $http({
                url: "http://...",
                method: "POST",
                data: jsonDataDetails,
                dataType: "json",
                timeout: 5000,
                contentType: 'application/json; charset=utf-8'
            })
                .then(function (res) {
                    var data = res.data;
                    responsedata=data.d;
                    return responsedata;

                },function (error) {
                    $scope.status = status;
                    console.log("Unable to update. No internet?");
                })
        }

我的目标是 var testing = getdetails('12345'); 为我提供该 ID 的响应数据,但我正在返回 Promise {$$state: Object...

我做错了什么?非常感谢!

您得到的输出不过是 $http.get 方法返回的承诺对象。基本上,您需要将 .then 函数放在 getdetails2 函数之上,以便在 resolve/reject.

时从 promise 对象获取数据

代码

getdetails2('12345').then(function(data){ //success callback
   //you will get data here in data parameter of function,
   var testing = data;
}, function(error){ //error callback
   console.log(error)
})