DEV Community

loading...

Discussion on: Making concurrent API calls in Node

Collapse
ironydelerium profile image
ironydelerium

This, pretty much:

server.get("/api/photos", async (req, res) => {
  const days = req.query.days
  const dates = generateDates(days)

  const requests = dates.map((date) => axios.get(`${URL}?api_key=${api_key}&date=${date}`));

  try {
    const result = await Promise.all(requests);
    res.status(200).json({ items: requests.length, photos: result.map(item => item.data) });
  } catch (err) {
    res.status(500).json({ error: String(err) });
  }
})
Enter fullscreen mode Exit fullscreen mode

There's also Promise.allSettled if you want all of the results, error or not.