0

I am using an Angular service as an interface for API calls. In this case JavaScript's asynchronous nature makes this difficult. Do you have any suggestions to how I should do it?

function getOrder(orderId) {
    $http({
        method: 'GET',
        url: '<api-url> + orderId'
    }).success(function (result) {
        /* --- getOrder should return parameter 'result' --- */
    });
}
1
  • 3
    convert it into promise pattern using .then function..do return data from it.and then the consumer method's .then will get called. Commented Sep 9, 2015 at 14:49

2 Answers 2

1

Better return the promise:

function getOrder(orderId) {
  return $http({
    method: 'GET',
    url: '<api-url>' + orderId
  });
}

Then, when calling:

getOrder("1").then(function(response) {
  // response.data contains the returned data
});

See https://docs.angularjs.org/api/ng/service/$http#general-usage


Please note the deprecation notice about success and error.

Sign up to request clarification or add additional context in comments.

Comments

0

Are you familiar with callback functions and promises? I think you should have an additional parameter in you getOrder function, the callback function, which you should call with the results or the error message with.

Here is an introduction for this: http://recurial.com/programming/understanding-callback-functions-in-javascript/

or just return the promise itself, as mentioned above!

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.