从http内部函数返回数据 [英] Return data from http inside function

查看:56
本文介绍了从http内部函数返回数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 this 参考,以从http请求中返回数据在函数内部:

I'm using this and this reference, to return data from an http-request inside a function:

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...

My goal is that var testing = getdetails('12345'); gives me the responsedata for that ID, but I'm getting back Promise {$$state: Object...

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

What am I doing wrong? Thanks a lot!

推荐答案

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

The output you are getting is nothing but a promise object which has been returned by the $http.get method. Basically you need to put .then function over getdetails2 function for getting data from the promise object when it resolve/reject.

代码

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)
})

这篇关于从http内部函数返回数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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