0

I am trying to upload a file/store using node and saving the file in Gird FS. Below is the code sample. The upload functionality works perfectly. Due to node's async nature, response is immediately sent back to the browser. I want to hold the response until the callback function gets executed. Note : i also tried to send final response inside call back function but still it did not work.

Please shed some ideas.

const multer = require("multer");
const GridFsStorage = require("multer-gridfs-storage");
const mongoose = require("mongoose");
mongoose.connect(CONFIG.dbConfig, {useNewUrlParser: true, useUnifiedTopology: true} );

var storage = new GridFsStorage({
  url: CONFIG.dbConfig,
  options: { useNewUrlParser: true, useUnifiedTopology: true },
  file: (req, file) => {
    return {
      bucketName: "xyz",
      filename: `${file.originalname}`
    };
  }
});

const viewPage = (req, res) => {
  try {
    
    var uploadFile = multer({ storage: storage }).single("file");
     uploadFile(req, res, function(err) {
      if (req.file == undefined) {
        return res.send(`You must select a file.`);
      }

      /* code to save anthother Schema */
      fileDetails.save(function(err) {
        if (err) throw err;
      });
      
    });
    
    return res.send(`File has been uploaded.`);
  } catch (error) {
    console.log(error);
    return res.send(`Error when trying upload image: ${error}`);
  }
};

module.exports = {
  getPage:  viewPage
};
4

1 回答 1

1

You will have to use async and await

// convert multer function to async await
function uploadFile(req) {
    return new Promise(resolve => {
       var uploadFile = multer({ storage: storage }).single("file");
       if (req.file == undefined) {
          return resolve([`You must select a file.`, null]);
       }else {
          // do something
          return resolve([null, data])
       }
    });
}
const viewPage = async (req, res) => {
  try {
     let [err, data] = await uploadFile(req)
      // check error and send response
      // convert do async await similarly for below fileDetails.save  
 
      /* code to save anthother Schema (change this to async await) */
      fileDetails.save(function(err) {
        if (err) throw err;
      });
      
    });
    
    return res.send(`File has been uploaded.`);
  } catch (error) {
    console.log(error);
    return res.send(`Error when trying upload image: ${error}`);
  }
};
于 2020-08-06T17:21:00.617 回答