1

I am using try catch statements. In my try statement I only want to return values which I got from functions that are defined outside try catch statement. However, the values are undefined.

I am adding a code snippet below:

const request = User.friendRequest(userId, friendId, (err, friendshipRequest) => {
  if (err) throw err;
  return friendshipRequest;
});

If I console.log(friendshipRequest) inside the callback function, everything works like charm, I get the JSON object that I wanted. However when I try to use const request in try catch statement - const request becomes undefined.

try {
  return res.status(201).json({
    error: false,
    request,
  });
} catch (e) {
  return res.status(400).json({ error: true, message: e.errsmg });
}

The full code looks like this

export const sendFriendRequest = async (req, res) => {
  const { userId, friendId } = req.params;

  const request = await User.friendRequest(userId, friendId, (err, friendshipRequest) => {
    if (err) throw err;
    return friendshipRequest;
  });

  try {
    return res.status(201).json({
      error: false,
      request,
    });
  } catch (e) {
    return res.status(400).json({ error: true, message: e.errsmg });
  }
};
  • `User.friendRequest` doesn't appear to return a promise when you pass a callback to it. – Bergi May 07 '17 at 21:02
  • possible duplicate of [undefined value in try catch](http://stackoverflow.com/q/43836415/1048572)?! – Bergi May 07 '17 at 21:03

2 Answers2

1

I assume User.friendRequest() returns a promise and can also work with callbacks, but you shouldn't use both at the same time (await uses the promise, but you're also passing a callback).

Just use the promise:

export const sendFriendRequest = async (req, res) => {
  const { userId, friendId } = req.params;

  try {
    const request = await User.friendRequest(userId, friendId);
    return res.status(201).json({
      error: false,
      request,
    });
  } catch (e) {
    return res.status(400).json({ error: true, message: e.errsmg });
  }
};
robertklep
  • 198,204
  • 35
  • 394
  • 381
0

When I have changed my code to this and posted with postman - everything works as expected, but still I would like to only pass values from functions to my try/catch. Any suggestions?

try {
    User.friendRequest(userId, friendId, (err, friendshipRequest) => res.status(201).json({
      error: false,
      friendshipRequest,
    }));
  } catch (e) {
    console.log(e);
    return res.status(400).json({ error: true, message: e.errsmg });
  }