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
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 thethen
call. It comes down to doing this: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 valuefalse
.The
await
operator ensures that this value (false
ortrue
) is assigned toexists
when the second promise fulfills.I hope this clarifies it.
access
is a notable exception in this regard, it acts as a replacement forexists
, which is deprecated and doesn’t have a counterpart infs.promises
.The example is technically correct but may look confusing because the role of
toBool
may not seem obvious, andasync..await
is mixed withthen
, which is generally a bad practice.A more verbose but less confusing way to write it is: