U
U
uniquerichboy2021-11-18 21:23:13
JavaScript
uniquerichboy, 2021-11-18 21:23:13

Is async await correct usage?

Please tell me if I’m using async await correctly, I’m already confused how to work with them correctly, since for example you can’t immediately put async on everything and put await everywhere, then it will write an error, since there are more functions inside, but it looks somehow crutch and wanted to know if I'm doing the right thing?

try {
        socket.on("exit", async function (team) {
          await axios.post(process.env.REACT_APP_API_URL + 'api/games/remove', {
            game: MATCH_ID, team,
          }).then(async function (response) {
            await dispatch({ 
              type: UPDATE_GAME, 
              game: response.data.game, 
              team_a: response.data.team_a,
              team_b: response.data.team_b,
            });
            await dispatch({ 
              type: ACCEPT, 
              accepts: false, 
            });
          });
        });
      } catch (e) {
        console.error(e);
      }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
profesor08, 2021-11-18
@profesor08

This is where await waits for the callback to complete, not the request. If dispatch is not a promise, then await before it is also not needed. Also, the try / catch block will not react in any way to exceptions in a promise or callback. Roughly speaking, the code does not do what you want from it.
If you need to catch exceptions, then you need to do it where they are thrown. And this is the request and its processing. Adding a listener will most likely not throw an exception, unless there is a gross bug. And you can’t catch an exception when calling a callback, since it will be called sometime later, when this code has already worked.

socket.on("exit", async () => {
  try {
    const response = await axios.post(
      process.env.REACT_APP_API_URL + "api/games/remove",
      {
        game: MATCH_ID,
        team,
      },
    );

    await dispatch({
      type: UPDATE_GAME,
      game: response.data.game,
      team_a: response.data.team_a,
      team_b: response.data.team_b,
    });

    await dispatch({
      type: ACCEPT,
      accepts: false,
    });
  } catch (err) {
    console.error(err);
  }
});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question