Precedence issues chaining async code

This is part of the Semicolon&Sons Code Diary - consisting of lessons learned on the job. You're in the javascript category.

Last Updated: 2024-11-23

If you need access to an attribute on something async, use parentheses in order to avoid being surprised by precedence. Await has a lower precedence than member access

  // Incorrectly returned false when `success` was true
  const apiTokenIsValid = await api.validateApiToken()?.success;
  // this worked
  const apiTokenIsValid = (await api.validateApiToken())?.success;

Resources