Taking an input array of IDs, on each item I have to sequentially execute a fetch request, and then perform a database operation using the returned results.
IDs = [1,2,3,4]
I have two options for this,
- Using Promise.all, I perform all of the fetch calls up front and push the results to an array. Then, once all the calls have been made, i take this resulting array and loop through it to perform my DB operation on each result.
let requests = ids.map(id => {
return new Promise((resolve, reject) => {
request({
uri: <API url>+‘?id=' + id,
method: ‘GET’
},
(err, res, body) => {
if (err) { reject(err) }
resolve(body)
})
})
})
Promise.all(requests).then((body) => {
body.forEach(res => {
if (res)
productsToReturn.push(JSON.parse(res).productInfo)
})
}).catch(err => console.log(err))
- Using a reducer that performs the fetch call and the database operation on each ID before moving onto the next.
return files.reduce((chain,currentFile) => {
return chain.then(_ => download(currentFile));
},Promise.resolve())
}
reductiveDownloadChain(mockFiles)
Is one of these methods a better choice? How do I know which to pick?