I am trying to call a GET API under three different configurations for region
parameter, and combine the results into a single result
object which I want the API to return as a JSON.
Here is my approach, which uses an array of Promises.
app.get("/api/v2/leagues/games", (req, res) => {
const regions = ['uk', 'us', 'au'];
let result = {};
let promiseArray = regions.map(region => {
return new Promise((resolve, reject) => {
const uri = `https://api.the-odds-api.com/v3/odds/?apiKey=${functions.config().theoddsapi.key}&sport=${req.query.league}®ion=${region}&mkt=${req.query.mkt}`;
console.log(uri);
request.get(uri, (error, response, body) => {
if (body) {
result[region] = JSON.parse(body).data;
resolve(body);
}
else {
console.error("error:", error);
console.log("statusCode:", response && response.statusCode);
reject(error);
}
});
});
});
Promise.all(promiseArray).then(() => {
return res.json(result)
}).catch(() => response.errorCode);
});
});