Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

212
Visualizações
Difference between async(req,res,next) and async(req,res,()=>{}

I recently came across this code and I fail to understand why the next has been omitted from the protect function(inside protectandauth function) while it is included in the protect function originally. I want to know the difference between protect=async(req,res,next)and protect=async(req,res,()=>{}.

I also see that even though next is omitted in the protect(the one inside protectandauth) function, it is still used in the code after the 'if' statement, how is that possible?

Code:

export const protect = async (req, res, next) => {
  if (
    req.headers.authorization &&
    req.headers.authorization.startsWith("Bearer")
  ) {
    let token;
    token = req.headers.authorization.split(" ")[1];
    const decoded = jwt.verify(token, "kris");

    req.userId = decoded.id;

    try {
      req.user = await User.findById(req.userId).select("-password");

      next();
    } catch (error) {
      res.status(401).json(error.message);
    }
    if (!token) {
      res.status(404).json("no token found");
    }
  }
};

export const protectandauth = async (req, res, next) => {
  protect(req, res, () => {
    if (req.userId == req.params.id) {
      next();
    } else {
      res.status(401).json("not authorised");
    }
  });
};
about 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

Every callback where you access req and res, you can also access next. next is a function that's used to to say "pass to the next callback", knowing that a request can be processed by multiple callbacks, like so:

const firstCallback= (req, res, next) => {}
const secondCallback= (req, res, next) => {}
app.get("/", firstCallback);
app.get("/", secondCallback);
// or using this syntax
app.get("/", firstCallback, secondCallback);

In the above example, when a request comes to /, it's handled first by firstCallback, and it's one of the two below scenarios (otherwise the request will hang, and the user won't get a response):

  1. It stops the request by calling one of the res methods, like res.status(401).json("not authorised");
  2. It says "pass to the next callback" calling next(), and then secondCallback handles it.

If next is omitted from the parameters, you will be calling next() where it's undefined, and that throws an error. Speaking of the use of protect function, if you notice, there is next as part of protectandauth's parameters, and it's that next that's used inside protect's third parameter, which is:

 () => {
    if (req.userId == req.params.id) {
      next();
    } else {
      res.status(401).json("not authorised");
    }
  }

And in this specific code you have, the above function is passed as next in protect's definition.

about 4 years ago · Santiago Trujillo Relatório

0

We use next if we want to pass our request to the next middleware in line. Maybe in protect, the programmer might not want to pass the req to the next middleware but in protectandauth he want to pass the req to the next middleware if this condition turns out to be true

if (req.userId == req.params.id) {
      next();
}
about 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda