Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning angular promise from a function that resolves the promise very quickly

I am writing an asynchronous javascript function that will be called by consumers to get certain data. Following is the simple implementation that I wrote initially (error handing and other stuff removed for clarity).

function getData(callback){
    if (data is available as a JavaScript object){
        callback(data);
    }else{
        getAsyncData(function(data){
             //some transformations on data
             callback(data); 
        });
    }
}

What is important to note is that getData can return data quickly if data is already available as a JavaScript object.

I want to replace this implementation with the one that returns a promise object to the caller. This fiddle shows sample implementation - http://fiddle.jshell.net/ZjUg3/44/

The question - Since getData can return quickly, can there be a possiblity where getData is resolving the promise even before caller has established handler chain using then method? Just to simulate this, in the fiddle if i call then method inside setTimeout function (with zero delay), callback doesn't get called. If i call the then method outside of the setTimeout function, callback gets called. I am not sure if this is even a valid concern or valid usecase. I am quite new to angularjs development and would appreciate your views :)

like image 332
Chintan S Avatar asked Feb 15 '23 19:02

Chintan S


1 Answers

If you want getData() to return a $q promise instead of using a callback, I'd do the following refactor using $q.when() and usual $q.resolve():

function getData()
{
    if (data is available as a JavaScript object) {
        return $q.when(data); // resolves immediately
    } else {
        var q = $q.defer();
        getAsyncData(function(data){
             //some transformations on data
             q.resolve(data); 
        });
        return q.promise;
    }
}
like image 80
Fernando Piancastelli Avatar answered Feb 18 '23 07:02

Fernando Piancastelli