How to handle asynchronous code in a for-loop nodejs?

30 Views Asked by At

I have an upload function as so:

const upload = async (req, res) => {
    let fileData = [];
    if (req.files) {
        // Save image to cloudinary
        let uploadedFile 
        let buffer
        for(let i = 0; i< req.files.length; i++){
            try {
                buffer = req.files[i].buffer
                uploadedFile = cloudinary.uploader.upload_stream(
                    {
                        folder: "products",
                        resource_type: "image",
                    }, 
                    function(error, result) {
                        fileData.push({
                            fileName: req.files[i].originalname,
                            filePath: result.secure_url,
                        })
                    }
                )
                streamifier.createReadStream(buffer).pipe(uploadedFile)
            } catch (error) {
                res.status(500);
                console.log(error)
                throw new Error('Image could not be Uploaded');
            }
        }
        res.json(fileData)
    }
}

The idea is to upload the pictures using multer memoryStorage, get the buffer, turn the buffer into a readable stream using streamifer and then upload it to cloudinary using cloudinary's upload_stream function. The problem is that the function takes too long to run and by the time it finishes running and i push the result into fileData, res.json() has already run so essentially, i would be returning an empty array. I can fix this by putting the res.json() into the function as so:

function(error, result) {
   fileData.push({
   fileName: req.files[i].originalname,
 })
 res.json(fileData)
}

But in the case of multiple pictures, the for-loop would stop running so res.json() has to be outside the for loop. Essentially, I need to wait for upload_stream.function() to run then the for-loop would continue. How can i go about it? A direct answer would be much appreciated as i have checked similar questions and have been unsuccessful.

0

There are 0 best solutions below