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 :

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.

Leave a Reply