0

currently I am reading these two answers to better understand the problem and get better at javascript:

wait for async task to finish Promises in AngularJS and where to use them?

But at the moment I have this code:

function getRegistration(id) {
    var numRegistered = 0;
    api.search({num: id, state: "done"})
        .then(function(response) {
            numRegistered = response.data.content.length;
        )};

    console.log(numRegistered);
}

now I can expect numRegistered to be 0 because it probably executes that statement before the asynchronus call has finished. I am finding it hard to understand how to do this so that I wait for the call, assign the value and return it...the solutions appear to be use a call back function or use a promise. Could someone help me (yes I come from an object oriented background...).

api.search basically executes an $http.get.

Community
  • 1
  • 1
user2405469
  • 1,953
  • 2
  • 22
  • 43
  • You can not return the value in a classical way because it suggests that the execution is sync and waits for your result. But that's not the case with async js. Here you pass it as parameter to your next function or event callback like the promise (success or fail...)events. This is just the way of js codeing – kidwon Sep 17 '14 at 11:31

1 Answers1

1

Here is the promise approach:

function getRegistration(id) {
    return api.search({num: id, state: "done"}); // we just return the promise
}

And then, in your controller or a service, you'd wait for it to resolve:

getRegistration(id).then(function(res) {
    var numRegistered = res;
    // rest of the code here
});

But again, although now your function returns something (a promise), you still need to wait for the promise to be resolved before having numRegistered available.

This is very similar to what happens inside your original .then callback, but here we've moved the non-getRegistration code outside of the getRegistration function, assuming that getRegistration is inside some service that shouldn't know about the rest of your code.

Shomz
  • 37,421
  • 4
  • 57
  • 85