Using Multer upload function in async mode with nodejs

Viewed 4344

I need make a conversion of a Multer Midware function('upload') using callback to works in async mode using promises.

I tried to transform the upload function in a promise.

The image sent to server continues being saved as before, but my code throw an error as:

(node:3568) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): undefined
(node:3568) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the
 Node.js process with a non-zero exit code.

when I execute the function

var resp=await uploadAsync(req, res);

What am I doing wrong?

//server code

'use strict';
const express = require('express');
const router = express.Router();
const pool = require('./pool');     // my database pool module, using promise-mysql
const Errors = require('./mysql_errors'); // my collection of custom exceptions
const HttpStatus = require('http-status-codes');
var path = require('path')
var fs = require('fs')
const fileDir='./public/images/uploads'

//imagens
const multer = require('multer');
const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, fileDir)   
    },

    filename: function (req, file, cb) {
        cb(null, Date.now() + '-' + file.originalname);
    }
})

const upload = multer({ storage: storage}).single('foto');

function uploadAsync(req,res){
    return new Promise(function(resolve,reject){
         upload(req,res,function(err){
             if(err !== null) return reject(err);
             resolve();
         });
    });
}

router.post('/foto/:id',uploadAsync, async function(req,res,next){  
        try{
            var resp=await uploadAsync(req, res);
        }catch(err) {
            return res.status(500).send({ success:false, message: 'Erro', results:{} }); // 404
        }
});


module.exports=router;
1 Answers
if(err !== null) return reject(err);
resolve();

in those conditions, you have to keep like

if(err !== undefined) return reject(err);
resolve();

as the error will be undefined is the call back returns true.

Related