jeudi 27 juin 2019

Conditionally send responses in an Express app

I'm curious wether you can write if statements in an Express app to conditionally execute your code without providing else statements.

if(pred) {
  doSomething()
}
return foo;
calcBar(); // doesn't run.

Above is the synchronous code that stops execution after the return statement.

My Express function looks like this:

app.get('/matches', async function(req, res) {
  try {
    const data = await someGraphQLCall();
    if(data.length === 0) {
      res.json({ message: "No data." });
    }
    const someOtherData = await someOtherGraphQLCall(data.foo);
    res.json({ someOtherData });
  } catch (err) {
    res.json({err})
  }
}

I know because of this question that code after the first res.json might still be executed. Is there a way to stop that? I don't want the second GraphQL call to execute if the first if condition is met. Is that possible without using else ?

Aucun commentaire:

Enregistrer un commentaire