0

How do i pass values from an array, as parameters to a get request REST api call and save all responses received, for each item per api request.

I have the following file format:

Const Data = [
  {
      user: '123456'
     
    },
   
  { 
      user: '123456',
    
    },
   
  {
      user: '123456',
     
    },
   

  }
]

the get url for the API is:

router.get(`/courses/:user)

What i'm trying to do:

pass all values of Data as parameter to the request, so it will look like this:

localhost:8000/courses/123456

This will happen for as many items in data, then gather together all the responses in on json output.

I have tried using forEach but no luck so far.

Expected result should be a Json data with all responses:

var output = [{response1},{response2}, {responds3}]
5
  • 1
    Call fetch() in a loop, saving the returned promises in an array. Then use Promise.all() to wait for all of them to finish, and make an array of the results. Commented Nov 16, 2022 at 22:55
  • thanks for the reply, can you help with a code example? Commented Nov 16, 2022 at 22:58
  • I'm trying to find a previous question that already answers this. I'm sure it's been asked many times. Commented Nov 16, 2022 at 23:03
  • Found none though cos i checked, if you find any, kindly share please. Many Thanks. Commented Nov 16, 2022 at 23:05
  • I can find lots of them that use jQuery, it's harder to find non-jQuery instances. Although the general idea should be the same, just replace $.ajax with fetch and $.when with Promise.all Commented Nov 16, 2022 at 23:08

1 Answer 1

1
const Data = [
  {
      user: '123456'
     
    },
   
  { 
      user: '123456',
    
    },
   
  {
      user: '123456',
     
    },
  }
];

const result = await Promise.all(Data.map(({user}) => apiCall(user)));
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.