Function inside a service returns populated array as empty - why?

Im probably misunderstanding something fundamental here:

function recipients() {
  var sources = [];
  var sharelist = [];
  Thread.list({},
    function(threads) {
      var i = 0;
      angular.forEach(threads, function(thread) {
        if (!(thread.id in sources)) {
          sources.push(thread.id);
          Thread.source(thread,
            function(res) {
              sharelist[i] = {};
              sharelist[i] = { value: thread.id, name: res.name };
              $log.debug('SHARELIST[' + i + ']:', sharelist[i]);
              i++;
            },
            $log.error
          );
        }
      });
      $log.debug('SOURCES', sources);
      $log.debug('SHARELIST', sharelist);
      return sharelist;
    },
    function(err) {
      $log.error(err);
      return null;
    }
  );
};

I see SHARELIST[i] printed out in my logs with proper objects but if I call this function from another service I always get back an empty array. What am I misunderstanding here?

Can you post the code where you call it from another service?

Perhaps it is something to do with running asynchronously, but I need to see calling code

The calling code (for now) is just some test code in an event handler so Im just logging:

$log.debug('SHARED WITH:', recipients());

Hmm… Im now wrapping this call inside an ionicPopup and its working as expected, so you’re probably right in that it was simply an asynchronous/timing issue.