Reputation: 3927
I have the following functions of Promises:
const func1 = () => new Promise((resolve, reject) => {
console.log('func1 start');
setTimeout(() => {
console.log('func1 complete');
resolve('Hello');
}, 1000);
});
const func2 = () => new Promise((resolve, reject) => {
console.log('func2 start');
setTimeout(() => {
console.log('func2 complete');
resolve('World');
}, 2000);
});
And to execute those functions in series, I use:
const promiseSerial = funcs =>
funcs.reduce((promise, func) =>
promise.then(result => func().then(Array.prototype.concat.bind(result))),
Promise.resolve([]))
And to call:
promiseSerial([func1, func2]).then(values => {
console.log("Promise Resolved. " + values); // Promise Resolved. Hello, World
}, function(reason) {
console.log("Promise Rejected. " + reason);
});
And everything works fine, because I can have an array of values in series according to the order of the functions.
So, my question is:
How can I pass parameters between functions? I mean, I want to pass a parameter from func1
to func2
. I have thought maybe in the resolve
, but it does not works.
Any ideas???
Upvotes: 1
Views: 101
Reputation: 494
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
const func1 = (FIRST_PARA) => new Promise((resolve, reject) => {
console.log('func1 start, the first parameter is ' + FIRST_PARA);
setTimeout(() => {
console.log('func1 complete');
resolve('Hello');
}, 1000);
});
const func2 = (FIRST_PARA, LAST_PARA) => new Promise((resolve, reject) => {
console.log('func2 start, the received last parameter is ' + LAST_PARA);
setTimeout(() => {
console.log('func2 complete');
resolve('World');
}, 2000);
});
const promiseSerial = (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);
});
Upvotes: 1