Trusted answers to developer questions

How to use the reflect function in JavaScript's async module

Get Started With Data Science

Learn the fundamentals of Data Science with this free course. Future-proof your career by adding Data Science skills to your toolkit — or prepare to land a job in AI, Machine Learning, or Data Analysis.

Reflect

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.

Usage

The following example demonstrates how the reflect function can be used.

import reflect from 'async/reflect';
var fs = require('fs');
// Callback function
function print(err, res){
// Accessing data
if (res){
if (res.value != undefined){
console.log(res.value);
}
else {
console.log(res.error);
}
}
else{
console.log(err);
}
}
// Working function
function helloWorld(callback){
callback(null, "Hello World!");
}
// Incorrect function
function 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 reflect
var hello = reflect(helloWorld);
var fileReader = reflect(readFile);
// Calling functions
hello(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.

RELATED TAGS

async
asynchronous programming
javascript
error handling
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?