Search code examples
angularjsangular-resource

How to wait for multiple requests based on _.each iteration in angular using $resource


Hi I have a method that does multiple request based on _.each iteration. What I want to do is initialize vm.job = job in the getAllJobSublinesByJobline after the _.each iteration

    var vm = this;

    function getAllJobSublinesByJobline () {
        return $resource( '/api/joblines/get_all_jobsublines_by_jobline/:pageLimit', {
            'jobLineId' : '@jobLineId',
            'page'      : '@page',
            'search'    : '@search',
            'sortField' : '@sortField',
            'sortType'  : '@sortType'
        } );
    }

    function getJobsublinesByJoblineId ( joblines, job ) {
        _.each( joblines, function ( jobline ) {
            if ( parseInt( jobline.num_sublines ) ) {
                var jobsublineFetchDetails = {
                    'pageLimit' : 10,
                    'jobLineId' : jobline.id
                };
                return getAllJobSublinesByJobline().save( jobsublineFetchDetails ).$promise.then( function ( jobsubline ) {
                    jobline.jobsublines = jobsubline.data;
                    job.joblines.push( jobline );
                } );
            }
            job.joblines.push( jobline );
        } );
        vm.job = job; // initializes right away even though _.each iteration is not finished yet
    }

My problem is that it initializes right away even though the _.each iteration has not finished fetching data yet. Why is this happening?


Solution

  • From the Docs:

    It is important to realize that invoking a $resource object method immediately returns an empty reference (object or array depending on isArray). Once the data is returned from the server the existing reference is populated with the actual data.

    -- AngularJS $resource API Reference

    So as said in another answer, push promises, and use $q.all.

    function getJobsublinesByJoblineId ( joblines, job ) {
        var promises = [];
        _.each( joblines, function ( jobline ) {
            if ( parseInt( jobline.num_sublines ) ) {
                var jobParams = {
                    'pageLimit' : 10,
                    'jobLineId' : jobline.id
                };
                var details = getAllJobSublinesByJobline().save( jobParams );
                promises.push(details.$promise);
            }
        } );
        $q.all(promises).then (function (detailsArray) {
             //assemble job object
             vm.job = job;
        });
    }