Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How does JavaScript evaluate this boolean conversion to arrive at the expected output?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading