All files / piscosour/lib/utils waterfall.js

0% Statements 0/31
0% Branches 0/9
0% Functions 0/6
0% Lines 0/31
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55                                                                                                             
'use strict';
 
const Waterfall = function(config) {
  this.logger = config.logger;
  this.config = config;
  this.n = 0;
  this.last = this.config.promises.length;
};
 
 
Waterfall.prototype.start = function() {
  this.logger.silly('Start promises');
  return new Promise((resolve, reject) => {
    this._run(resolve, reject);
  });
};
 
Waterfall.prototype._run = function(resolve, reject) {
 
  const _resolve = (result) => {
    this.logger.silly('_resolve', result);
    const isLast = this.n === this.last - 1;
    if (result && result.skip || isLast) {
      resolve(result);
    } else {
      this.n++;
      this._run(resolve, reject);
    }
  };
 
  const _reject = (err) => {
    this.logger.silly('_reject', err);
    reject(err);
  };
 
  if (this.n < this.last) {
    this.logger.debug('Executing promise', this.n, 'of', this.last);
    try {
      const promise = this.config.promises[this.n].fn.apply(this.config.promises[this.n].obj, this.config.promises[this.n].args);
 
      if (promise) {
        promise.then(_resolve, _reject);
      } else {
        this.logger.debug('Promise: (', this.n, ') is not defined!');
        _resolve({skipped: true});
      }
    } catch (e) {
      _reject(e);
    }
  } else {
    resolve();
  }
};
 
module.exports = Waterfall;