Mar1009
Mar1009

Reputation: 811

How to call a function inside a promise with reduce function in javascript

Here is my array

arr = [2,3,4]

here is my functions

function functionMultpily(p1, p2) {
  return( p1 * p2);  
}

function functionADD(p1, p2) {
  return( p1 + p2);  
}

I need to use this functions in a promise such that it should complete one after another by taking the values from arr by using Reduce function.

Upvotes: 1

Views: 1431

Answers (3)

trincot
trincot

Reputation: 350300

First make sure your functions return promises, for instance by returning Promise.resolve(a*b) instead of a*b.

Then apply reduce on the array of values, where in each iteration you accumulate (chain) one promise to the next. There second argument of reduce (initial value) is not used, so the first callback that reduce makes is with the first and second array value as arguments. As we want the accumulator to be a promise, and at the start it clearly isn't, apply Promise.resolve to the accumulator:

function multiply(a, b) {
  let c = a * b;
  console.log(a + " * " + b + " = " + c);
  return Promise.resolve(c);
}

function add(a, b) {
  let c = a + b;
  console.log(a + " + " + b + " = " + c);
  return Promise.resolve(c);
}

let arr = [2,3,4];
let functions = [multiply, add];

arr.reduce((acc, b, i) => Promise.resolve(acc).then(a => functions[i-1](a, b)))
   .then(console.log);

The accumulator is from then on always a promise that resolves to an (intermediate) result (like a product or sum). In the reduce callback, you chain a then on that promised value. Once resolved, execute the desired function (add or multiply) passing it both the resolved value and the next value from the array. The result of then() is again a promise, which will be the accumulator value in the next iteration.

Finally, print out the reduced value that reduce will promise.

Upvotes: 3

shrys
shrys

Reputation: 5940

You could use Promise.resolve() along with Promise.prototype.then() as follows:

const arr = [1, 2, 3, 4, 5, 6];

const sleep = ms => new Promise(res => setTimeout(res, ms));

const add = (a, b) => sleep(500).then(() => a + b);
const multiply = (a, b) => sleep(500).then(() => a * b);

arr
  .reduce((p, x) => p.then((y) => add(x, y)), Promise.resolve(0))
  .then(sum => console.log(sum));

arr
  .reduce((p, x) => p.then((y) => multiply(x, y)), Promise.resolve(1))
  .then(product => console.log(product));

Upvotes: 1

stchr
stchr

Reputation: 211

this is the way to call function one after other.

Promise.series([
    new Promise(function functionMultpily(p1, p2) {
  resolve( p1 * p2);  
}),
    new Promise(function functionADD(p1, p2) {
  resolve( p1 + p2);  
})
    ]).then(function(val){
// do any further computation here.
        console.log(val);
    }).catch(function(e){
        console.error(e.stack);
    });

Upvotes: -2

Related Questions