Angular Promises: Best Practices and Pros / Cons of Different Methods

I am learning Angular and I came across two call approaches that return promises. I would like to know if one approach is better than the other and / or when you will use each.

First technique:

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

    if (myData) {
        // call to backend was previously made and myData is already loaded 
        deferred.resolve(myData);
    } else {
        // get data from server
        $http.get(my_url_endpoint).then(function(response) {
            // cacheResult() will set myData = response.data
            deferred.resolve(cacheResult(response));
        });
    }

    return deferred.promise;
}

      

Second technique:

function getSomeDataFromServer() {

    if (myData) {
        // call to backend was previously made and myData is already loaded 
        return $q.when(myData);
    } else {
        // get data from server
        return $http.get(my_url_endpoint).then(function(response) {
            // cacheResult() will set myData = response.data
            return cacheResult(response);
        });
    }
}

      

+3


source to share


1 answer


Always prefer the second option. The first option is the anti-pattern, which is commonly seen when the developer does not fully understand the nature of promises. Deferred Objects ( var deferred = $q.defer();

) are used when you have asynchronous code that uses callbacks but needs to work with your code based on a promise .

The most asynchronous things you do in Angular are return promises, so you usually only use deferrals when working with a third party library that relies on callbacks.



In this example, $ http returns a promise itself, so creating a new deferred object is not required. Returning the $ http promise itself is enough.

+4


source







All Articles