if 语句不是 运行,它包含一个异步函数
if statement not running which includes an async function
我在 if/else 语句中有一个异步函数。我只想在使用它之前检查请求正文中是否有文件,否则会引发错误。为什么会这样?有什么更好的方法可以解决这个问题吗?
//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")
}
你的外部 if
什么都不做,因为 typeof banner
永远不会是值 undefined
(尽管它可能是字符串 "undefined"
)。
typeof
returns 带有类型名称的 字符串 ,因此 if (typeof banner !== 'undefined')
应该可以工作。
但是,很可能您在这里甚至不需要 typeof
- if (banner !== undefined)
甚至 if (banner)
也应该适用于您的情况。
我在 if/else 语句中有一个异步函数。我只想在使用它之前检查请求正文中是否有文件,否则会引发错误。为什么会这样?有什么更好的方法可以解决这个问题吗?
//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")
}
你的外部 if
什么都不做,因为 typeof banner
永远不会是值 undefined
(尽管它可能是字符串 "undefined"
)。
typeof
returns 带有类型名称的 字符串 ,因此 if (typeof banner !== 'undefined')
应该可以工作。
但是,很可能您在这里甚至不需要 typeof
- if (banner !== undefined)
甚至 if (banner)
也应该适用于您的情况。