Skip to content

ipanasenko/reduce-for-promises

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

12 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

This is a simple implementation of Promise.reduce, that is available in Bluebird

Installation

npm install reduce-for-promises

Usage

import reduce from 'reduce-for-promises';

Example

Callback function will iterate to next item only after previous item's promise is resolved

const result = await reduce([1, 2, 3, 4], function (acc, item) {
  return new Promise(function (resolve) {
    setTimeout(function () {
      resolve(acc + item);
    }, 1000);
  });
}, 0);
console.log(result); // 10

You can set fourth argument to reduce if you want to set step size. For example, if you want two items to be processed at a time, here is the example

const delays = [1000, 100, 300, 200, 100];
const { sum } = await reduce([1, 2, 3, 4, 5], function (acc, item, i) {
  return new Promise(function (resolve) {
    setTimeout(function () {
      acc.sum += item;
      resolve(acc);
    }, delays[i]);
  });
}, {sum: 0}, 2);
console.log(sum); // 15

Please note that if you set step argument, make sure to use object as accumulator. Otherwise it won't be carried properly between callback iterations

About

No description, website, or topics provided.

Resources

License

Stars

Watchers

Forks

Packages

No packages published