1

I want to get data pass from a function, the data successfully return inside the success response. However I can't return the data from the function itself.

function getStatusPublished(dating, product) 
{
    var datas = "";

    var success = function(response, status, headers, config){
      datas = response;
    }

    var error = function(error, status, headers, config){
      datas = "error";
    }

    var cdnss = "htttp://application_ajax";
    $http.post(cdnss+"&pblishDateVacan="+dating+"&ProjectID="+product)
    .success(success).error(error);

    console.log(datas);
}

In the console.log, it just said undefined.

Please help. Thanks.

georgeawg
  • 48,608
  • 13
  • 72
  • 95
al_kasih_empatix
  • 127
  • 2
  • 11
  • you cannot return the data from the function. An http call is asynchronous and takes time to get data back. A function is synchronous and returns immediately. You probably want to return a promise from your function. – rob Jul 05 '16 at 15:34
  • Can you help me, please, how to do this with promise return? – al_kasih_empatix Jul 05 '16 at 15:36
  • Put `console.log(datas);` **INSIDE** the success function – Alon Eitan Jul 05 '16 at 15:36
  • Alon, I want to return the data from the function itself, not only from the success call. – al_kasih_empatix Jul 05 '16 at 15:36
  • There are some good video's on egghead.io for learning how to use promises https://egghead.io/lessons/angularjs-promises – rob Jul 05 '16 at 15:37
  • So what's @rob wrote is what you need to know about AJAX – Alon Eitan Jul 05 '16 at 15:38
  • Possible duplicate of [How do I return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Kevin B Jul 05 '16 at 21:11

1 Answers1

1

The $http.post method returns a promise; not data.

To return a promise, simply use a return statement.

function getStatusPublished(dating, product) {
    var url = "htttp://application_ajax";
    var postData = {};
    var params = {
      pblishDataVacan: dating,
      ProjectId: product
    };
    var config = { params: params };
    var promise = $http.post(url,postData,config);
    //return promise
    return promise;
}

To get the data from the promise, use the .then method:

var promise = getStatusPublished(d, p);

promise.then( function(response) {
    $scope.data = response.data;
    return response.data;
}).catch ( function(response) {
    console.log(response.status);
    throw response;
}); 
georgeawg
  • 48,608
  • 13
  • 72
  • 95