I am writing a code which check authorization from two different API calls in a promise.all method, in which if any one authorization fails, the respective res.send method would be thrown as an error, but there is an error : Cannot set headers after they are sent to the client
error showing on my console, where am I going wrong ?
On the screen, the res.send statement is displayed, but along with that, this error : Cannot set headers after they are sent to the client
error showing on my console. How do I fix this ?
I am writing the code in two different ways, but every time the same error is displayed.
1st way ( without .catch ) :
const isSubscribed = new Promise((resolve, reject) => {
apiGet("/isSubscribed", token).then(async (Response) => {
if (!isResStatusSubscribed(Response)) return res.status(401).send({ errorMessage: "Unauthorized Request." })
})
})
const isAdmin = new Promise((resolve, reject) => {
apiGet("/isAdmin", token).then(async (response) => {
let isAdmin = response.data.Response.is_admin
if (!isAdmin) return res.status(403).send({ errorMessage: "User is not an Admin" })
})
})
Promise.all([isSubscribed, isAdmin]).then(async () => {
await insertLiveClassDB(req.body)
return res.status(200).send({ Response: "Success." })
});
2nd way ( with .catch ) :
const isSubscribed = new Promise((resolve, reject) => {
apiGet("/isSubscribed", token).then(async (Response) => {
if (!isResStatusSubscribed(Response)) reject(res.status(401).send({ errorMessage: "Unauthorized Request." }))
})
})
const isAdmin = new Promise((resolve, reject) => {
apiGet("/isAdmin", token).then(async (response) => {
let isAdmin = response.data.Response.is_admin
if (!isAdmin) reject(res.status(403).send({ errorMessage: "User is not an Admin" }))
})
})
Promise.all([isSubscribed, isAdmin])
.then(async () => {
await insertLiveClassDB(req.body)
return res.status(200).send({ Response: "Success." })
})
.catch(error => {
return error
});
I am new to express js and writing promise.all method, and really need help. Thank you in advance.