skip to Main Content

const toBool = [() => true, () => false]

The above line is used in this MDN guide to (seemingly) evaluate the output from Node’s fs.promises.access method as a boolean.

The snippet in question is below, paraphrased from the MDN example:

const toBool = [() => true, () => false];

const prepareFile = async (url) => {
  ...
  const exists = await fs.promises.access(filePath).then(...toBool);
  ... 
};

The code works as intended; I’m hoping for an explanation as to how the compiler evaluates these lines, as I can’t quite wrap my head around it.

As best as I can tell, when fs.promises.access returns undefined (a successful resolution, according to the Node docs for the access method), exists is set to true, while the return of an Error object sets exists to false.

Can someone explain how this line evaluates to arrive at true for exists in the snippet above?

2

Answers


  1. The access() method returns a promise that resolves when the accessibility check succeeds or that rejects when not.

    The then method returns a second promise. It can take two arguments: the first is a callback that will be executed when the first promise resolves, and the second is a callback that will be executed when the first promise rejects.

    How that second promise resolves depends on what the relevant callback returns (or throws).

    Now to your specific code. Note how then(...toBool) uses spread syntax to provide two arguments to the then call. It comes down to doing this:

    then(() => true, () => false);
    

    In case the first promise resolves (i.e. the accessibility check is successful), the first of these functions executes, ignores the argument, and makes the second promise fulfill with the value true. If on the other hand the first promise rejects (i.e. the accessibility check is not successful), the second of these callbacks executes, ignores the (error) argument, and makes the second promise fulfill with the value false.

    The await operator ensures that this value (false or true) is assigned to exists when the second promise fulfills.

    I hope this clarifies it.

    Login or Signup to reply.
  2. access is a notable exception in this regard, it acts as a replacement for exists, which is deprecated and doesn’t have a counterpart in fs.promises.

    The example is technically correct but may look confusing because the role of toBool may not seem obvious, and async..await is mixed with then, which is generally a bad practice.

    A more verbose but less confusing way to write it is:

    let exists;
    try {
      await fs.promises.access(filePath);
      exists = true;
    } catch {
      exists = false;
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search