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?
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.