Search code examples
angularjsangular-servicesngresource

how to wait until promise returns when using $resource


I have a my controller with an activate method which waits for promises to return before going forward.

        function activate() {
        var promises = [getNodesGroup(), getNodes()];
        common.activateController(promises, controllerId)
            .then(function () {
                log('Activated');
            });
    }

Both of the promises had similar approach to get the data and that was using $http in datacontext.getNodeGroups() and datacontext.getNodes() methods.one of which is like this

        function getNodesGroup() {
        return datacontext.getNodeGroups().then(function (response) {
            $scope.nodeGroups = response.data;
           //other logic
        });

All was working fine until now when i tried to use $resource for one of teh promises (getNodes()). my resource for node is setup like this

(function () {
'use strict';
var nodeServiceRoot = '/api/Nodes';

var GetAllNodesUrl = nodeServiceRoot + '/GetAllNodes';

angular.module('common.service')
.factory("nodeResource",["$resource","appSettings", nodeResource])
function nodeResource($resource, appSettings) {
    return $resource(appSettings.serverPath + GetAllNodesUrl);
}}());

and i am trying to consume it like this

        function getNodes() {
        $scope.nodes = nodeResource.query();
        $scope.nodes.$promise.then(function (response) {
            $scope.nodes = response;
            //other logic
        });

i don't know how to return getNodes() so that my activate functions wait for it before proceeding. right now whats happening is that sometime both functions are run when it hits log('Activated'); line of activate functions and some time only one promise with old $http approach (getNodeGroups()) is run but not the other.


Solution

  • well i guess the answer was very simple. i was missing 'return' in getNodes() so what worked for me is

     function getNodes() {
        $scope.nodes = nodeResource.query();
      **return**  $scope.nodes.$promise.then(function (response) {
            $scope.nodes = response;
            //other logic
        });