all files / liquidjs/src/util/ promise.js

100% Statements 17/17
100% Branches 0/0
100% Functions 4/4
100% Lines 15/15
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            77× 77× 95×   77×                 571× 571× 571× 1007× 986× 955×   571×      
/*
 * Call functions in serial until someone resolved.
 * @param {Array} iterable the array to iterate with.
 * @param {Array} iteratee returns a new promise.
 * The iteratee is invoked with three arguments: (value, index, iterable).
 */
function anySeries (iterable, iteratee) {
  var ret = Promise.reject(new Error('init'))
  iterable.forEach(function (item, idx) {
    ret = ret.catch(e => iteratee(item, idx, iterable))
  })
  return ret
}
 
/*
 * Call functions in serial until someone rejected.
 * @param {Array} iterable the array to iterate with.
 * @param {Array} iteratee returns a new promise.
 * The iteratee is invoked with three arguments: (value, index, iterable).
 */
function mapSeries (iterable, iteratee) {
  var ret = Promise.resolve('init')
  var result = []
  iterable.forEach(function (item, idx) {
    ret = ret
      .then(() => iteratee(item, idx, iterable))
      .then(x => result.push(x))
  })
  return ret.then(() => result)
}
 
exports.anySeries = anySeries
exports.mapSeries = mapSeries