Ad

Conditionally Send Responses In An Express App

- 1 answer

I'm curious whether 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 ?

Edit:

As the question I linked above mentioned, using a return statement is a bad option because:

it also makes it less meaningful and vague, cause it uses incorrect semantics. If you are not using the value from the function, then you shouldn't return one.

Ad

Answer

You can use return keyword on the first response to immediately return from the function.

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

Edit:

As an alternative, you can split the logic of the data and building up response. This way you can use return and it's easier to read:

app.get('/matches', async function (req, res) {
    try {
        const data = await getDataFromGraphQLCall();
        res.json(data);
    } catch (err) {
        res.json({ err })
    }
});

async function getDataFromGraphQLCall() {
    const data = await someGraphQLCall();
    if (data.length === 0) {
        return { message: "No data." };
    }
    const someOtherData = await someOtherGraphQLCall(data.foo);
    return { someOtherData };
}
Ad
source: stackoverflow.com
Ad