The functions as they stand are not currently promises. They do, however, follow the async pattern in node.
You can either use something like promisify-node or do it yourself:
// define the first 2 promises by calling firstFunc with inputs
var promise1 = new Promise(function resolver(resolve, reject) {
firstFunc(input1, function(err, res){
if(err) reject(err);
resolve(res);
});
var promise2 = new Promise(function resolver(resolve, reject) {
firstFunc(input2, function(err, res){
if(err) reject(err);
resolve(res);
});
// When promise1 & 2 resolve, execute the then handler
Promise.all([promise1, promise2]).then(function (arr) {
// Grab the resolved values
var arr1 = arr[0];
var arr2 = arr[1];
// return a new promise that is resolved when middleFunc completes
return new Promise(function resolver(resolve, reject) {
middleFunc(arr1, arr2, function(err, res){
if(err) reject(err);
resolve(res);
});
});
}).then(function (arr3) { // Execute this when middleFunc completes
return lastFuntion(arr3); // This function looks synchronous
}).catch(function (err) {
// Handle any errors along the way
});
Edit: If you want to create promise1 and promise2 more generically, write a helper function:
// Helper function to construct a promise by calling firstFunc with input
var firstFuncHelper = function (input) {
return new Promise(function resolver(resolve, reject) {
firstFunc(input, function(err, res){
if(err) reject(err);
resolve(res);
});
};
var promise1 = firstFuncHelper(input1);
var promise2 = firstFuncHelper(input2);
// Rest of code above remains
Promise.all. Depending on what promise lib you are using, also have a look atPromise.joinor thespreadmethod.