Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am new to Javascript and Angularjs. I wanted to know , how to call a function asynchronously without waiting for it to return from it.

Please let me know and if there is some example then it would be very helpful.

Regards, nG

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
140 views
Welcome To Ask or Share your Answers For Others

1 Answer

Use Angular's deferred:

function myAsyncFunction() {
    var deferred = $q.defer();

    //..
    setTimeout(function() {
        deferred.resolve({ message: "resolved!" });
        // or deferred.reject({ message: "something went terribly wrong!!" });
    }, 1000);
    //..

    return deferred.promise;
}

myAsyncFunction()
    .then(function(data){
        // success
        console.log("success", data.message);
    }, function(data) {
        // fail
        console.log("error", data.message);
    }).finally(function() {
        // always
    });

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...