I realize there have been posts about Promises and/or the Promise all function not working as expected because ExpressJS does not natively wait for all of the data to resolve, but I am baffled as to why my code is still not waiting on the Promises to resolve before sending the data back. The logs print the data I would like to send to the client. I've made the functions more generic for this post, but the function structures have not been altered.
app.get('/some-endpoint', (req, res, next) => {
if(req) {
try {
return Promise.all([executeRequest(1, 2, 3), executeRequest(4, 5, 6), executeRequest(7, 8, 9), executeRequest(10, 11, 12)]).then(function(results) {
console.log(results, 'Request results')
res.status(200).send(results);
}).catch(function(err) {
return res.status(500).send(err);
});
} catch (e) {
console.log(e);
return res.status(500).json({status: 500, message: e.message});
}
} else {
return res.status(400).json({status: 400, message: 'Bad Request'});
}
});
That endpoint calls off to a function, executeRequest, which returns a Promise. The data from the response's "data" and "end" states are being resolved and logged through the console, but of course the response body is empty. I have refactored these function many times, trying to follow other answers and tutorials on Promises and Express, but I haven't been able to get the Promise all results to be returned in the response body. I am using the https module. Any help would be really appreciated.
function executeRequest(a, b, c) {
return new Promise(function(resolve, reject) {
var options = {
host: host,
path: '/some-other-endpoint-to-call-off-too',
method: 'GET',
port: '443',
headers : {
"Authorization" : a+b+c
}
};
const callback = function(response) {
var str = ''
response.on('data', function (chunk) {
str += chunk;
console.log(str, 'data');
});
response.on('end', function () {
console.log(str, 'on end');
resolve(str);
});
}
let req = https.request(options, callback);
req.end();
});
}