When I asynchronously map an array, Promise.all was supposed to make the function wait until all the promises are resolved. However, Promise.all shows as undefined. Here is my code. Please can someone tell me what I am doing wrong? Thanks.
router.get("/vehicle_reports/interior-pictures", auth, async (req, res) => {
const fileKeysObj = await Report.findOne({ orderId: req.params.jobId }, {
"vehicleInterior": 1
})
const fileKeysArray = fileKeysObj.interior
console.log("fileKeysArray: ", fileKeysArray);
//Retrieve the files from S3
const files = fileKeysArray.map(async (item) => {
const params = {
Bucket: process.env.AWS_BUCKET_NAME,
Key: item.fileKey
}
await s3.getObject(params, async (err, data) => {
if (err) {
throw new Error()
}
else {
const base64Data = base64Arraybuffer.encode(data.Body)
const contentType = data.ContentType
const fileName = item.fileName
return { base64Data, contentType, fileName }
}
})
})
console.log( files) //Pending promise
await Promise.all(files)
console.log( files) //Undefined
res.send(files) //Sends empty array
})
Replace the inside of the map
call to look like this.
const params = {
Bucket: process.env.AWS_BUCKET_NAME,
Key: item.fileKey
}
return new Promise((res, rej) => {
s3.getObject(params, async (err, data) => {
if (err) {
rej('FAILED');
} else {
const base64Data = base64Arraybuffer.encode(data.Body)
const contentType = data.ContentType
const fileName = item.fileName
res( { base64Data, contentType, fileName });
}
})
});