Monday, 17 April 2017

Accumulate promise values "functionally"

Say I have this:

function getAllPromises(key, val): Promise {

 const subDeps = someHash[key];
 const acc = {}; // accumulated value

 return subDeps.reduce(function (p, k) {

  return p.then(v => getAllPromises(k, v)).then(function (v) {
        acc[k] = v;
        return acc;
   });

 }, Promise.resolve(val))

}

is there a way to avoid having to declare a separate variable:

const acc = {}; // accumulated value

and somehow return that from the promise chain instead?

Ultimately the acc variable is what gets resolved from the promise chain, but wondering if I can somehow avoid having to declare it "outside" the chain.



via Alexander Mills

No comments:

Post a Comment