You just need to use .then correctly, and not discard the result of the first request
const request = require('request-promise');
const getInfo = (uri) => {
// Return new promise
return request({
method: 'GET',
uri: uri,
json : true,
headers: {
'User-Agent': 'Request-Promise'
}
});
}
// using promise.then
const result = (url1, url2) => getInfo(url1)
.then(val1 => getInfo(url2)
.then(val2 => val1.array.concat(val2.array))
);
// or async/await
const result = async (url1, url2) => {
const val1 = await getInfo(url1);
const val2 = await getInfo(url2);
return val1.array.concat(val2.array);
};
// both requests done at the same time
const result = (url1, url2) => Promise.all([
getInfo(url1),
getInfo(url2)
]).then(([val1, val2]) => val1.array.concat(val2.array));
export result;
// usage
const fn = require("./module.js"); // whatever you call the above file
fn("url1", "url2").then(result => {
// use result here
});
To explain each incarnation of result
- it may be easier to write it out using regular functions so I can add comments
const result = function(url1, url2) {
return getInfo(url1)
.then(function(val1) {
return getInfo(url2)
.then(function(val2) {
return val1.array.concat(val2.array));
})
})
}
Usually you try to avoid "nesting" .then's like this, but since the end result requires both val1 and val2, it's unavoidable (not really, but, lets say it is)
This is where async/await shines
const result = async (url1, url2) => {
const val1 = await getInfo(url1);
const val2 = await getInfo(url2);
return val1.array.concat(val2.array);
};
There's no need to even rewrite that, because it's clear!
However, you want to run in Parallel
const result = (url1, url2) => Promise.all([
getInfo(url1),
getInfo(url2)
]).then(([val1, val2]) => val1.array.concat(val2.array));
Promise.all takes an array of promises, and returns a promise that resolves to the array of resolved results
([val1, val2]) => //rest of code
in case you didn't know is like
(results => {
let val1 = results[0];
let val2 = results[1];
// rest of code
So, that should be fairly easy to understand as it is