Skip to content Skip to sidebar Skip to footer

How To Pass Parameters In An Array Of Functions Using A Series Of Promises

I have the following functions of Promises: const func1 = () => new Promise((resolve, reject) => { console.log('func1 start'); setTimeout(() => { console.l

Solution 1:

In func2() replace

const func2 = ()

to

const func2 = (PARAMETER)


In promiseSerial() replace

promise.then(result => func()

to

promise.then(result => func(result[0])


console.log the PARAMETER in func2 will show you the string 'Hello'



To send parameter to func1 and if you have multiple funcs

constfunc1 = (FIRST_PARA) => newPromise((resolve, reject) => {

  console.log('func1 start, the first parameter is ' + FIRST_PARA);
  setTimeout(() => {
    console.log('func1 complete');
    resolve('Hello');
  }, 1000);
});

constfunc2 = (FIRST_PARA, LAST_PARA) => newPromise((resolve, reject) => {

  console.log('func2 start, the received last parameter is ' + LAST_PARA);
  setTimeout(() => {
    console.log('func2 complete');
    resolve('World');
  }, 2000);
});

constpromiseSerial = (funcs, firstParameter) => funcs.reduce((promise, func) =>
promise.then(result =>func(firstParameter, result[result.length - 1]).then(Array.prototype.concat.bind(result))), Promise.resolve([]))


var firstParameter = 12;

promiseSerial([func1, func2], firstParameter).then(values => {
  console.log("Promise Resolved. " + values); // Promise Resolved. Hello, World
}, function(reason) {
  console.log("Promise Rejected. " + reason);
});

Post a Comment for "How To Pass Parameters In An Array Of Functions Using A Series Of Promises"