One option, as Alexander Promise.all(functionA(), functionB()) writes, use Promise.all(functionA(), functionB()) . This performs two functions at the same time. If this is what you want, you can use this answer. If, however, you want them to happen one after another, and then also be able to pass the result to another handler, you can do this:
function functionA() { return new Promise(resolve => resolve(1)); } function functionB() { return new Promise(resolve => resolve(2)); } function functionC(first, second) { return first + second; } functionA() .then(result => Promise.all([result, functionB()])) .then(function([first, second]) { return functionC(first, second); }) .then(result => { console.log(result); });
Functions are obviously simplified, but the great thing about Promises is that it doesn't matter: we don't care how complicated they are or how long they take. Yay Promises!
The smartest thing is that Promise.all doesn't mind if the values ββyou pass are not Promises. If they represent any other value, they are considered a promise that is immediately resolved. (In the same way, you can do Promise.resolve(42).then(...) .) That way we can do Promise.all([result, functionB()]) . This says: "Give me a promise to be resolved when you get the final value for result and functionB() and pass both values ββto." This happens directly in the case of result and at some unspecified time in the case of functionB .
The returned values ββare then passed as an array of the next then function.
.then(function([first, second]) { return functionC(first, second); })
Then it receives the values ββas an array (see using destructuring in the parameter list) and passes these values ββto functionC . Then we do the last function then to show the result.
source share