The reflect
function ensures that a function returns an output even when an error occurs.
This function wraps the target function and returns an object with either a value
or an error
property.
The following example demonstrates how the reflect
function can be used.
import reflect from 'async/reflect';var fs = require('fs');// Callback functionfunction print(err, res){// Accessing dataif (res){if (res.value != undefined){console.log(res.value);}else {console.log(res.error);}}else{console.log(err);}}// Working functionfunction helloWorld(callback){callback(null, "Hello World!");}// Incorrect functionfunction readFile(callback, fileName){done = false;try {fs.readFile(fileName, 'utf8', function(err, data) {if (err == null){callback(null, data);done = true;}else {callback(err)}});}catch(err){callback(err)}}// Using reflectvar hello = reflect(helloWorld);var fileReader = reflect(readFile);// Calling functionshello(print);fileReader(print, '/educative.txt');
This program demonstrates the behavior of reflect
with an erroneous function call and a correct call.
The correct function, helloWorld
, simply returns the value, Hello World
to the callback. The erroneous function, readFile
, attempts to read data from a non-existing text file. When it is unable to do so, it calls the callback with an error.
Essentially, the first parameter in the callback is the error and the second is the resultant value (if any). When there is no error, the callback is called with null
as its first argument and followed by any result value in front of it. On the other hand, if an error occurs, users can call the callback with a non-null, first parameter.
Inside the callback, the first parameter is always null
even when a non-null first parameter has been passed. This is because everything is passed inside a result object (named as res
in this example’s callback function). The result object has an error
and value
member. The error
member contains the value of the first argument in the call to the callback, and the value
member contains the second argument.
Free Resources