'Making multiple Node Express API request calls

I followed this guide https://herewecode.io/blog/step-by-step-guide-create-first-api-with-node-express/ to create a simple Node, Express API and it all works fine, I then changed the API call to interact with SWAPI (Star Wars API). Again all works ok. But my question is if I want to make multiple calls to the SWAPI and get 2 or 3 responses and display them together, how would I do that? is express request the best thing to use?

GitHub for guide: https://github.com/gael-thomas/First-API-With-Node-And-Express-example

Here is my basic app with the API call on the route

Index.js

const express = require('express')
const api_helper = require('./API_helper')
const app = express()
const port = 3000

app.get('/', (req, res) => res.send('Welcome to Make REST API Calls In Express!'))

app.get('/getAPIResponse', (req, res) => {
  api_helper.make_API_call('https://swapi.dev/api/people/1/')
    .then(response => {
      console.log(response[0])
      res.json(response)
    })
    .catch(error => {
      res.send(error)
    })
})

app.listen(port, () => console.log(`App listening on port ${port}!`))

module.exports = app

API_helper.js

const request = require('request')

module.exports = {
  make_API_call : function(url){
    return new Promise((resolve, reject) => {
      request(url, { json: true }, (err, res, body) => {
        if (err)
          reject(err)
        resolve(body)
      });
    })
  }
}

So where I'm calling https://swapi.dev/api/people/1/ and getting my response how would I call /people/2/ and /people/3/ and display them all together?



Solution 1:[1]

Promise.all([
  api_helper.make_API_call('https://swapi.dev/api/people/1/'),
  api_helper.make_API_call('https://swapi.dev/api/people/2/'),
  api_helper.make_API_call('https://swapi.dev/api/people/3/')
])
.then(function([response1, response2, response3]) {
  // Process the three responses
})
.catch(error => {
  // Error occurred in any of the three requests
  res.send(error)
});

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Heiko Theißen