Create an object or associative array with elements of an existing array and the result of a callout for each element

This is in the context of a node express route. I receive a get request with a query param that is a list of IDs. Now I need to make a call-out for each ID and store the result of the callout in an array or object. Each element of the first array (containing the IDs) need to be mapped to its corresponding result from the call-out. I don’t have a way to modify the endpoint that I’m hitting from this route so I have to make single calls for each ID. I’ve done some research and so far I have a mixture of code and sudo code like this:

const ids = req.query.ids;
const idMembers = Promise.all(ids.map(async id => { 
  // here I'd like to create a single object or associative array
  [ id: await callout(id); ]
}));

When all promises resolved I need the final result of idMembers to be like: (The response will be an object with nested arrays and objects I’ve just simplified it for this post but I need to grab that from the res.payload)

{
  '211405': { name: 'name1', email: 'email1@test.co' },
  '441120': { name: 'name2', email: 'email2@test.co' },
  '105020': { name: 'name3', email: 'email4@test.co' }
}

Oh and of course I need to handle the callout and the promise failures and that’s when my lack of experience with javascript becomes a real issue. I appreciate your help in advance!!

Some extra thought I’m having is that I’d have to map the results of the resolved promises to their id and then in a separate iteration I can then create my final array/object that maps the ids to the actual payloads that contain the object. This is still not answering any of my questions though. I’m just trying to provide as much information as I’ve gathered and thought of.

99 thoughts on “Create an object or associative array with elements of an existing array and the result of a callout for each element”

  1. I think this is among the moswt important information for me.
    And i’m glad reading your article. But want to remark on some general things, The websiite style is great, the
    articles is really nice : D. Good job, cheers
    web page

    Reply

Leave a Comment