0

I am looking to make a GET call over a few parameters (with request.js) , combine the result and return it as my own GET API (with express.js) - like so:

app.get("myapi", (req. res) => {
  parameters = ["a", "b", "c"]
  let result = {}

  parameters.forEach(param => {
    const uri = `https://api.exampleApi.com/?parameter=${param}`
    request.get(uri, (error, response, body) => {
      result[param] = body.data;
    });
  });
  res.json(result);
});

However, the result returned for this is empty {}. How can I combine multiple calls?

EDIT: Here is my new code with an array of Promises.

app.get("/api/v1/leagues/games", (req, res) => {
  const promiseRequest = (sport, region, mkt) => {
    return new Promise(resolve => {
      const theOddsApiUrl = `https://api.the-odds-api.com/v3/odds/?apiKey=${functions.config().theoddsapi.key}&sport=${sport}&region=${region}&mkt=${mkt}`; 
      request.get(theOddsApiUrl, (error, response, body) => {
        if (body) {
          resolve(body)
        }
      });
    })
  }
  const makeRequest = (sport, mkt) => {
    let allRegionsOdds = {};
    Promise.all([
      promiseRequest(sport, 'uk', mkt),
      promiseRequest(sport, 'us', mkt),
      promiseRequest(sport, 'au', mkt)
    ]).then(body => {
      return allRegionsOdds[region] = body;
    }).catch();
  }
  const response = makeRequest(req.query.sport, req.query.mkt);
  res.json(response);
});
isaacsultan
  • 3,784
  • 3
  • 16
  • 29
  • `request.get` is async, hence `res.json(result)` is invoked **before** the `get` requests are performed, resulting in the empty object you're getting. Create an array of promises and, once all the promises are resolved, call `res.json(result);`. – briosheje Jun 25 '19 at 15:18
  • Thank you @briosheje. I've edited my answer with an approach as you outlined - however, it still is not quite there. Would appreciate any suggestions. – isaacsultan Jun 26 '19 at 11:17
  • That's still not there because you're missing the Promise concept. I highly suggest you to check a tutorial about these, since you will encounter them **a lot** in node and everything javascript related. I rewrote your initial code in the approach I would actually follow, feel free to take a look at it: https://pastebin.com/qdxs9Zm9 – briosheje Jun 26 '19 at 11:49
  • Keep in mind that `Promise.all` runs the `then` block with all bodies present. Meaning that `body` should be `bodies`. Furthermore `makeRequest` has no return value making `response` always `undefined`. – 3limin4t0r Jun 26 '19 at 13:00
  • Thank you @briosheje, that's hugely useful. – isaacsultan Jun 27 '19 at 10:44
  • @3limin4t0r I see! It should then be `allRegionsOdds[region] = body; resolve()` – isaacsultan Jun 27 '19 at 10:45

0 Answers0