0

I am trying to resize and upload multiple files using multer. It's working but the problem is when I am sending the data back it is sent before even the data is processed. So I am getting an empty list. I am new to nodejs tried solutions online but couldn't find the right one for me. Can anyone help me solving this problem? How can I push data into the list before sending the response?

the code is Attached below...

router.post('/ads/images', upload.array('images',5), async(req,res)=>{
console.log(req.files);

var data = []
await req.files.every(async(file)=>{
    var imageBuffer = await sharp(file.buffer).png().resize({
        width:250,
        fit: sharp.fit.cover,
        position: sharp.strategy.entropy
    }).toBuffer()
    var thumbnailBuffer = await sharp(file.buffer).png().resize({
        width:150,
        height:150,
        fit: sharp.fit.cover,
        position: sharp.strategy.entropy
    }).toBuffer()
    console.log({imageBuffer,thumbnailBuffer});

    data.push({imageBuffer,thumbnailBuffer})
})



console.log(data);

res.send(data)
},(error,req,res,next)=>{
    res.status(400).send({error:error.message})
})
Support Ukraine
  • 978
  • 6
  • 20
theblue5.o
  • 45
  • 1
  • 5

2 Answers2

0

The problem is in your every method. Use regular loops in async methods.

Please use a regular for loop instead and apply once only the sharp transforms.

for(let file of req.files) {
   (your code here)
}

Using async/await with a forEach loop

Mattia Rasulo
  • 1,236
  • 10
  • 15
0

Your await call is not doing anything because every is not asynchronous. Switch from every to map then use Promise.all(..) to wait for all promises returned by map to complete:

await Promise.all(req.files.map(async(file) => {
  // ...
}))
James
  • 697
  • 5
  • 23