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.

7
  • 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. Commented Jul 5, 2016 at 15:34
  • Can you help me, please, how to do this with promise return? Commented Jul 5, 2016 at 15:36
  • Put console.log(datas); INSIDE the success function Commented Jul 5, 2016 at 15:36
  • Alon, I want to return the data from the function itself, not only from the success call. Commented Jul 5, 2016 at 15:36
  • There are some good video's on egghead.io for learning how to use promises egghead.io/lessons/angularjs-promises Commented Jul 5, 2016 at 15:37

1 Answer 1

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;
}); 
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.