user2405469
user2405469

Reputation: 2003

javascript asynchronus function

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.

Upvotes: 0

Views: 80

Answers (1)

Shomz
Shomz

Reputation: 37701

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.

Upvotes: 1

Related Questions