I'm working on a function that make a certain amount of requests based on many ids. And then it picks the id of the resulting elements.
I would like to kind of propagate the id i used for the request in the response. Something like this: (illustrative only)
const fetchSomeIds = async (ids, Service) => {
const requests = ids.map(id => { return { url: `/something/` + id + `/something-else`}});
const responses = await Promise.all(requests.map(
request => Service.get(request.url)
));
const someIds = responses.map(element => {return {id: id/*(used in request)*/, some_id: element.data.some_id};});
return someIds;
};
So if i use ids=[27,54] and i get some_id=133 and some_id=32. the response should look like this:
[
{
"id": 27,
"some_id": 133
},
{
"id": 54,
"some_id": 32
}
]
Since Promise.all
preserves the order, you can access the original array at the same index:
const someIds = responses.map((element, index) => {
return {id: ids[index], some_id: element.data.some_id};
});
However, it might be simpler to just put the processing all in a single map
callback:
function fetchSomeIds(ids, Service) {
return Promise.all(ids.map(async id => {
const request = {url: `/something/` + id + `/something-else`};
const response = await Service.get(request.url);
const element = response;
return {id, some_id: element.data.some_id};
}));
}