I am trying to retrieve data at multiple API endpoints simultaneously and aggregate the result to be sent back to the client as one response.
However, when trying to return data from async.parallel
, I get an undefined
result. I think this is because the result
code is being executed before it is returned, but I am not sure.
I would like to pass an array of ids to the server, get their metadata, combine their metadata into one object, and send a single object back to the client.
function doSomething() {
for(let i=0; i<req.map.length; i++) {
stack[i] = (callback) => {
let data = subroute(req, res, req.map[i])
callback(null, data)
}
}
async.parallel(stack, (err, result) => {
if(err) {
// Handle error
} else {
console.log(result) // Logs undefined
res.json([result]) // Would like to send this result back to the client
}
})
}
function subroute(req, res, num) {
request({
url: 'https://example.com/api/endpoint/' + num
},
(error, response, body) => {
if(error) {
res.json({ "error": error })
} else {
let i = {
name: body.name,
age: body.age,
}
return i
}
})
}
How can I accumulate the results of many API endpoint responses on the server and send the back as one response to the client?