0

The issue

I have 5 work queues and each queue has 5 tasks.

First, I make an API call to get all work queues. I then send an ID from each queue to another endpoint which gets me the tasks for that queue.

I'm trying to push all tasks from all queues into one array, so ideally the end product would be an array of 25 tasks.

Due to Angular's asynchronous nature, I'm having trouble getting all the data into the right place at the right time.

My current code

var getAllTasks = function () {
  var deferred = $q.defer();
  var allTasks = [];

  qSrv.getQueues().then(function (response) {

    // Loop through all queues

    response.data.forEach(function (e, i) {

      // Get Queue task list by passing in Global Unique Identifier to endpoint

      qSrv.getQueueByQueueGuid(e.workQueueGuid).then(function (queue) {

        // Push all tasks within task list to one array

        queue.data.taskList.forEach(function (ee, ii) {
          ee.queueName = e.name;
          allTasks.push(ee);
        });
      });
    });

    // Resolve promise with arrays of all 25 tasks

    deferred.resolve(allTasks);
  })

  return deferred.promise;
}

Conclusion

I know there's something funky going on with the promises not finishing before being passed along to the next step, but I don't know how to structure it to avoid this problem.

I would appreciate any and all help, thank you.

ClaytonAlanKinder
  • 313
  • 1
  • 3
  • 15
  • I'm not sure if `allTasks` can be used as a shared memory object like that. That being said, you're calling `deferred.resolve(allTasks)` but at the point you're doing that, you don't know if the `.then` part of your `getQueueByQueueGuid(...).then` has actually executed. Basically you need to store all promise objects and do `.then` when they're all done. – apokryfos Jun 29 '16 at 15:24
  • Cool, thank you. I tried implementing $q.all at some point, but I think that's more for fulfilling all promises at once while I'm trying to fulfill one promises and then use data from that one promise to fulfill the rest. – ClaytonAlanKinder Jun 29 '16 at 15:31
  • Why are you fetching the queues two times instead of just once? `getQueues` should return the all the queues with their tasks. Also, you're implementing the [deferred antipattern](http://stackoverflow.com/questions/23803743/what-is-the-explicit-promise-construction-antipattern-and-how-do-i-avoid-it) by creating unnecessary new patterns. – Daniel B Jun 29 '16 at 15:56
  • @DanielB You're correct, it should have been done that way and I brought it up to our API guys. All in all, we ended up taking a different path so this wasn't necessary. Thank you for your help though, I appreciate it. – ClaytonAlanKinder Jul 01 '16 at 14:15

0 Answers0