I have a nodeJS web server that calls another api to get data, then (ideally) returns that data to the web page. I am using the request-promise library and trying to use Promise.all() to no avail.
What I have so far:
app.get('/endpoint', (req, res) => {
var url = 'some url';
var dataObject = {};
var promise1 = rp(url).then( (data) => {
//process data into dataObject
}
url = 'another url';
var promise2 = rp(url).then( (data) => {
//process data into dataObject
}
//same thing for promise 3...
Promise.all([promise1, promise2, promise3]).then(res.send(dataObject));
});
The problem is that res.send(dataObject) is not waiting for the promises to finish, so it's sending an empty object. I'm not very familiar with promises and am trying to learn more about them through this, but things aren't doing what I'm expecting. If I were to guess at what's happening, when calling rp().then(), .then() is causing the promise to resolve, and then it executes the code inside .then() after "resolving".
What I want is the code inside .then() to execute, then once all promises have finished their individual data processing, I want it to execute the .all().then() to return that data, but how would I go about doing this?