I have this piece of code. I make an writeRecords
request and then i do it again.
The next request i put in an array and use an Promise.all()
My question is:
What if requests.push(writeClient.writeRecords(timestreamParams).promise())
has an error, will it be an unhadled Promise error, or will the try / catch
catch the error?
Because its in an loop it can be that the first element in the array has already sent back an response while the other data is still in the loop so i am not sure where the error will occur?
let requests = []
const chunkSize = 100
for (let i = 0; i < Records.length; i += chunkSize) {
const chunk = Records.slice(i, i + chunkSize)
const timestreamParams = {
DatabaseName: db_name,
TableName: TimeSpanRawE[table_name],
Records: chunk,
}
await writeClient
.writeRecords(timestreamParams)
.promise()
.catch(() => {}) // Silent error
// Successfully retry same writeRecordsRequest with same records and versions, because writeRecords API is idempotent.
requests.push(writeClient.writeRecords(timestreamParams).promise())
}
try {
return Promise.all(requests).then((res) => ok(res))
} catch (error) {
return err({ error, params })
}
2
Answers
Yes, your code can lead to unhandled promise rejections, if one of the promises in the
requests
array rejects before thePromise.all
is reached (due to the loop being suspended on theawait
). It cannot happen if the loop were run synchronously.You should be using either the concurrent version
or the sequential version
but not the mix between them. If you really needed to, the
.catch(() => {}) // Silence error
needs to go on the promise that you are notawait
ing immediately (i.e. the ones you put in the array).I would put the retry logic in a separate function to make some separation of concerns. My usual way is to add to the
Promise
:Promise.retry
.Also your requests are independent from each other so you could execute them in parallel. We use
Array::map()
for that to get an array of promices