twitst4tz

twitter statistics web application
Log | Files | Refs | README | LICENSE

race.js (1250B)


      1 "use strict";
      2 module.exports = function(
      3     Promise, INTERNAL, tryConvertToPromise, apiRejection) {
      4 var util = require("./util");
      5 
      6 var raceLater = function (promise) {
      7     return promise.then(function(array) {
      8         return race(array, promise);
      9     });
     10 };
     11 
     12 function race(promises, parent) {
     13     var maybePromise = tryConvertToPromise(promises);
     14 
     15     if (maybePromise instanceof Promise) {
     16         return raceLater(maybePromise);
     17     } else {
     18         promises = util.asArray(promises);
     19         if (promises === null)
     20             return apiRejection("expecting an array or an iterable object but got " + util.classString(promises));
     21     }
     22 
     23     var ret = new Promise(INTERNAL);
     24     if (parent !== undefined) {
     25         ret._propagateFrom(parent, 3);
     26     }
     27     var fulfill = ret._fulfill;
     28     var reject = ret._reject;
     29     for (var i = 0, len = promises.length; i < len; ++i) {
     30         var val = promises[i];
     31 
     32         if (val === undefined && !(i in promises)) {
     33             continue;
     34         }
     35 
     36         Promise.cast(val)._then(fulfill, reject, undefined, ret, null);
     37     }
     38     return ret;
     39 }
     40 
     41 Promise.race = function (promises) {
     42     return race(promises, undefined);
     43 };
     44 
     45 Promise.prototype.race = function () {
     46     return race(this, undefined);
     47 };
     48 
     49 };