Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

if statement not running which includes an async function

I have an async function inside an if/else statement. I just want to check whether there is a file in the request body before even using it otherwise it throws an error. Why is this happening? And is there anything better I could do to handle the problem ?

//save image to cloudinary
if (typeof(banner) !== undefined) {
  //this piece of code is always executing even if the image is not present in request or is undefined
  cloudinary.uploader.upload(banner,
    async function(error, result) {

      if (error) {
        return res.status(409).send("Something went wrong while uploading image")
        console.log(error)
      }
      article.banner = result.url
      const savedArticle = await article.save()
      return res.status(201).send(JSON.stringify({
        redirect_uri: "/articles/" + savedArticle.slug
      }))

    })
} else {
  return res.status(400).send("Missing file")
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Your outer if does nothing, because typeof banner will never be the value undefined (it could be the string "undefined" though).

typeof returns a string with the type name in it, so if (typeof banner !== 'undefined') should work.

However, most likely you don’t even need typeof here – if (banner !== undefined) or even just if (banner) should work too in your case.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading