Araf
Araf

Reputation: 273

How to wait for a function to finish it's execution in angularJS?

I've a function named validityCheck() and it's returns valid if an user is valid and invalid if the user is invalid. I need to call this function from somewhere else and use the result in if-else condition.

Here's the function definition (This function is defined in a plain javascript library name library.js):

function validityCheck(userid, serviceid, system) {
    $(document).ready(function () {
        $.get("https:*******userValidation?serviceid=" + serviceid + "&userid=" + userid + "&system=" + system, function (data, status) {
            console.log(data);
            return data[0];
        });

    });
}

Now I want to do this (This code section is in my project's controller):

var validity = validityCheck($scope.userid, serviceid, 'abc');
if(validity=="VALID"){
    //do something
}else{
    //do something
}

I need to wait till I get the data. I think I need to use callback_ or something like that but I don't know how to do it.

Upvotes: 0

Views: 1331

Answers (1)

Jay Lord Ibe
Jay Lord Ibe

Reputation: 113

Why not return promise of angularjs $http and use then in your code like this?

function validityCheck(userid, serviceid, system) {
    let params = {
        userid: userid,
        serviceid: serviceid,
        system: system
    };
    let request = {
        url: "https:*******userValidation",
        method: "GET",
        headers: {"Content-Type": "application/x-www-form-urlencoded"},
        params: params
    };

    return $http(request).then((response) => {
        return response.data[0] ? response.data[0] : '';
    });
}

Usage:

validityCheck($scope.userid, serviceid, 'abc').then((validity) => {
    if (validity === "VALID") {
        //do something
    } else {
        //do something
    }
});

P.S. Don't forget to inject angularjs $http

UPDATE: Register library.js in angular

(function () {
    "use strict";

    angular
        .module("yourAngularModuleName")
        .factory("LibraryFactory", LibraryFactory);

        function LibraryFactory($http) {
            // Add your functions here...
        }

})();

UPDATE: Plain JavaScript Using The Existing Code

function validityCheck(userid, serviceid, system) {
    return new Promise((resolve, reject) => {
        $.get("https:*******userValidation?serviceid=" + serviceid + "&userid=" + userid + "&system=" + system, function (data, status) {
            console.log(data);
            resolve(data[0]);
        });
    });
}

Use the same code in the USAGE that I have provided.

Upvotes: 1

Related Questions