1

I have an API call but I don't know what kind of asynchronous code to use in such case, what is better for performance async / await VS Promise VS try / catch with async / await?

Here is the code:

here the exported function in the API file:

export const authenticateUser = (signInUser) => {
  return axios
    .post('user/sign-in', signInUser)
    .then((res) => res.data)
    .catch((err) => console.log(err);
};

now I'm gonna call this function from another file here are the examples that I have if there any better code let me know guys:

First instance:

  const authenticateUserHandler = () => {
    authenticateUser(user)
      .then((userId) => navigation.navigate('App'))
      .catch(() => setError(true));
  };

Second instance:

  const authenticateUserHandler = async () => {
    const userId = await authenticateUser(user);
    if (userId) {
      navigation.navigate('App');
    } else setError(true);
  };

Third instance:

 const authenticateUserHandler = () => {
    const userId = new Promise((resolve, reject) => {
      resolve(authenticateUser(user));
    })
      .then((Id) => Id)
      .catch(() => setError(true));

    return userId;
  };
MansouriAla
  • 177
  • 1
  • 1
  • 11
  • 3
    Performance? No difference at all. Where it'll differ is in the functionality and readability. The third is the explicit Promise construction antipattern. The second will have its errors percolate up to the caller. The first will handle errors in itself only, and call `setError` as a result. – CertainPerformance Apr 04 '21 at 19:10

0 Answers0