Thursday, 25 May 2017

How to combine a forEach with Promises.all

I am doing a function which uploads images to AWS from an input file field and then save the image URL and name to mongoDB. I am using NodeJS and MongoDB. Here is my example:

uploadFile(req, res, next) {

 let files = req.files;
 let images = [];


  files.file.forEach((file) => {

    uploadToAWS(file.path, {}, function(err, img) {

    if (err) { throw err; }

        // add path and name to images array

        images.push({
          path: img[0].url,
          name: img[0].name,
        });
    });
  });
    // Here the promises should resolve and save to MongoDB the array images
 },

Instead of saving to the database each time the loop iterate through the elements I just populate an array images and then save it to DB.



via Matt

No comments:

Post a Comment