I have tried a few different ways, basically I want to take out the cloudinary upload code from my routes and put it in a function that my route calls to make the code cleaner. But for some reason I cant get async/await to work/wait for the upload to complete before completing.
Here is an example of my route:
var fieldsUpload = upload.fields([{ name: 'image1', maxCount: 1 }, { name: 'image2', maxCount: 1 }])
router.post('/upload', fieldsUpload, async function (req, res, next) {
var url1 = await uploadToCloudinary(req.files['image1'][0].path);
console.log("Cloudinary url: " + url1);
var url2 = await uploadToCloudinary(req.files['image2'][0].path);
console.log("Cloudinary url: " + url2);
res.send("Succesfull Upload");
});
And this is my function:
async function uploadToCloudinary(image) {
try{
let url = await cloudinary.v2.uploader.upload(image);
}
catch(err){ console.log(err)}
}
// function uploadToCloudinary(image) {
// cloudinary.v2.uploader.upload(image, function(error, result) {
// if(error) {
// console.log(error);
// }
// else {
// console.log("Succesfully uploaded image to cloudinary!")
// return result.secure_url;
// }
// });
// }
I put the commented out function I had before so you could see I tried leaving the function not being async and just returning after the callback and have the await in the route but also didnt work. I also dont think I should need to await both in the function and route, but tried like that to see if it worked.
Not sure what I am missing/doing wrong.