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

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

javascript promise
javascript reduce
javascript promise example
javascript nested promises
reduce promise
javascript promise then
promise chaining
javascript reduce object

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.


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));

Using Promises, Modern functions return a promise that you can attach your callbacks to instead: before the completion of the current run of the JavaScript event loop. Basically, we reduce an array of asynchronous functions down to a� But, an example would be: top().then(function(result) { console.log(result); }. Before you ask, no, you cannot get result during the same function call - which is why we have promises and callbacks. – Katana314 May 10 '17 at 15:02


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);

Array.prototype.reduce(), The reduce() method executes a reducer function (that you provide) Calling reduce() on an empty array without an initialValue will throw a TypeError . { array} arr - promise arr * @return {Object} promise object */ function� Perform a map inside of a Promise.all. If the function performed inside of the map uses async/await, then it will complete before the next iteration (in order, not in parallel). The bonus is that the Promise.all resolves all of your promise values into an array. I’m posting this from my iPad, otherwise I’d give a code example.


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);
    });

Why Using reduce() to Sequentially Resolve Promises Works, Writing asynchronous JavaScript without using the Promise object is a lot like baking a cake function methodThatReturnsAPromise(nextID) { return new back into the same callback after each run, a feature unique to reduce() . It's an API that lives inside the browser and sits between your web pages… The code which uses a promise should call then function on that promise. It takes two anonymous functions as parameters. The first function executes if the promise is resolved and the second


Using reduce with nested async/await | by Khyati Thakur, at work where I had to use reduce inside nested async/await calls. function is a Promise, our accumulator should be a Promise, that we can� All Functions are Methods. In JavaScript all functions are object methods. If a function is not a method of a JavaScript object, it is a function of the global object (see previous chapter). The example below creates an object with 3 properties, firstName, lastName, fullName.


Sequential execution of Promises using reduce() � GitHub, function workMyCollection(arr) { return arr.reduce((promise, item) => { return handler inside an async function to wait for "accumulated promise" to resolve and � Promises allow us to do things in the natural order. First, we run loadScript(script), and .then we write what to do with the result. We must have a callback function at our disposal when calling loadScript(script, callback). In other words, we must know what to do with the result before loadScript is called.


Asynchronous Reduce in JavaScript, async function createLinks(links) { const results = []; for (link of links) This small code inside is, basically, a reducer, but with asynchronous flow! of the function to the promise, // even it is a synchronous call result = await� The Promise.resolve() method returns a Promise object that is resolved with a given value. If the value is a promise, that promise is returned; if the value is a thenable (i.e. has a "then" method), the returned promise will "follow" that thenable, adopting its eventual state; otherwise the returned promise will be fulfilled with the value. This function flattens nested layers of promise-like