onsdag 14 september 2016

Array with promises

First up, the problem: I needed to build an array of items based on multiple roles for a user in an Angular application. And the returning value had to be a promise. So first attempt was to build up the array with if-statements and Array.push, not very beautiful nor immutable, and then return it with $q.when(array).
So I figured that this could be done with multiple promises instead. So here’s what I came up with, fun with trolls and ogres.
 function creaturePromise(creature) {  
  function always() {  
   return $q.when([ "you", "are" ]);  
  }  
  function troll(creature) {  
   return $q(function(resolve) {  
    if (creature.isTroll()) {  
     resolve([ "troll" ]);  
    }  
    resolve([]);  
   });  
  }  
  function ogre(creature) {  
   return $q(function(resolve) {  
    if (creature.isOgre()) {  
     resolve([ "ogre" ]);  
    }  
    resolve([]);  
   });  
  }  
  return $q.all(always(), troll(creature), ogre(creature)).then(function(arr) {  
   return [].concat(...arr); // Flatten the array of arrays.  
  });  
 }  
Pretty self explaining, ey? Got a better way of doing it, please let us know :)
This blog post was authored by Micke Jönsson

Inga kommentarer:

Skicka en kommentar