Monday, December 9, 2013

.whenAll is an emerging concept in JavaScript for acting when all of the promises in an array of promises have resolved.

This is something you will have to roll yourself. For example this suggests you may do so in jQuery by aggregating instances of .when like so:

(function($) {
   $.whenAll = function() {
      return $.when.apply($, arguments);
   };
})(jQuery);

 
 

This touches on .when in jQuery in turn. At my place of work, we use a common library for interacting with Web SQL databases and it supports .whenAll as seen here:

populatePieChart: function(workOrders) {
   var pieChart = this.pieChart;
   var domNodeForLegend = dom.byId("table");
   var promises = workOrders.map(function(workOrder) {
      return workOrder.mdoElt.fetchWorkStatus().then(function(workStatus) {
         return workStatus;
      });
   });
   app.mdo.MDO.whenAll(promises).then(function(workStatuses) {
      var data = [];
      workStatuses.forEach(function(workStatus) {
         var isMatch = false;
         data.forEach(function(datum) {
            if (datum.text == workStatus) {
               datum.y = datum.y + 1;
               isMatch = true;
            }
         });
         if (!isMatch) {
            data.push({y: 1, text: workStatus});
         }
      });
      pieChart.setData(data);
      pieChart.prepChart();
      pieChart.prepLegend(domNodeForLegend);
   });
}

 
 

If I wanted to do the same thing without .whenAll there is a dirtier way to do it like so:

populatePieChart: function(workOrders) {
   var pieChart = this.pieChart;
   var domNodeForLegend = dom.byId("table");
   var data = [];
   var counter = 0;
   workOrders.forEach(function(workOrder) {
      workOrder.mdoElt.fetchWorkStatus().then(function(workStatus) {
         var isMatch = false;
         data.forEach(function(datum) {
            if (datum.text == workStatus) {
               datum.y = datum.y + 1;
               isMatch = true;
            }
         });
         if (!isMatch) {
            data.push({y: 1, text: workStatus});
         }
         counter++;
         if (counter == workOrders.length) {
            pieChart.setData(data);
            pieChart.prepChart();
            pieChart.prepLegend(domNodeForLegend);
         }
      });
   });
}

 
 

In both cases, I am attempting to aggregate data for the pie chart I made and I need to get a data point off of each workOrder in workOrders which is returned by way of a promise (we must go on a fishing excursion in the database) coming back from .fetchWorkStatus() thus creating the challenge for .whenAll to solve.

No comments:

Post a Comment