1
Callbacks Concept
Example 1: Code for reading a file synchronously (blocking code) in
Nodejs.
- Create a text file [Link] with the following content:
Hello Programmer!!!
Lern Nodejs with us
- Write a JavaScript code:
const fs = require("fs");
const filedata = [Link]('[Link]');
[Link]([Link]());
[Link]("End of Program execution");
Output:
Hello Programmer!!!
Learn Nodejs with us
End of Program execution
Example 2: Code for reading a file asynchronously (non-blocking code)
in Nodejs.
- Create a text file [Link] with the following content:
Hello Programmer!!!
Lern Nodejs with us
- Write a JavaScript code:
const fs = require("fs");
[Link]('[Link]', function (ferr, filedata) {
if (ferr) return [Link](ferr);
[Link]([Link]());
}
);
[Link]("End of Program execution");
2
Output:
End of Program execution
Hello Programmer!!!
Learn Nodejs with us
Example 3:
- Create a text file [Link] with the following content:
Hello Programmer!!!
Lern Nodejs with us
- Write a JavaScript code:
var fs = require("fs");
[Link]('[Link]', (err, data) => {
if (err) return [Link](err);
[Link]([Link]());
});
let i = 1;
while (i <=5) {
[Link]("The number is " + i);
i++;
}
Output:
The number is 1
The number is 2
The number is 3
The number is 4
The number is 5
Hello Programmer!!!
Learn Nodejs with us
3
[Link] – Events
Example: Given below is a simple example that binds two listeners to
the on event of EventEmitter class
// Import events module
var events = require('events');
// Create an eventEmitter object
var eventEmitter = new [Link]();
// Create an event handler as follows
var connectHandler = function connected() {
[Link]('connection successful.');
}
// Bind the connection event with the handler
[Link]('connection', connectHandler);
// Bind the data_received event with the anonymous function
[Link]('data_received', function(){
[Link]('data received successfully.');
});
// Fire the connection event
[Link]('connection');
// Fire the data_received
[Link]('data_received');
[Link]("Program Ended.");
Output:
connection successful.
data received successfully.
Program Ended.
4
More examples on callback functions
Example 1:
<h1>JavaScript Functions</h1>
<h2>Callback Functions</h2>
<p>The result of the calculation is:</p>
<p id="demo"></p>
<script>
function myDisplayer(something) {
[Link]("demo").innerHTML = something;
}
function myCalculator(num1, num2, myCallback) {
let sum = num1 + num2;
myCallback(sum);
}
myCalculator(5, 5, myDisplayer);
</script>
</body>
</html>
Output:
JavaScript Functions
Callback Functions
The result of the calculation is:
10
5
Example 2:
<!DOCTYPE html>
<html>
<body style="text-align: right">
<h1>JavaScript Functions</h1>
<h2>Callback Functions</h2>
<p id="demo"></p>
<script>
// Create an Array
const myNumbers = [4, 1, -20, -7, 5, 9, -6];
// Call removeNeg with a Callback
const posNumbers = removeNeg(myNumbers, (x) => x >= 0);
// Remove negative numbers
function removeNeg(numbers, callback) {
const myArray = [];
for (const x of numbers) {
if (callback(x)) {
[Link](x);
}
}
return myArray;
}
</script>
</body>
</html>
Output:
JavaScript Functions
Callback Functions
posNumbers will equal [4, 1, 5, 9], but it is not printed!
6
Asynchronous JavaScript
Functions running in parallel with other functions are called asynchronous
Example: Waiting for a Timeout
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Functions</h1>
<h2>setTimeout() with a Callback</h2>
<p>Wait 3 seconds (3000 milliseconds) for this page to change.</p>
<h1 id="demo"></h1>
<script>
setTimeout(myFunction, 3000);
function myFunction() {
[Link]("demo").innerHTML = "I love Nodejs !!";
}
</script>
</body>
</html>
Output (After 3 seconds):
JavaScript Functions
setTimeout() with a Callback
Wait 3 seconds (3000 milliseconds) for this page to change.
I love Nodejs !!
7
Instead of passing the name of a function as an argument to another
function, you can always pass a whole function instead:
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Functions</h1>
<h2>setTimeout() with a Callback</h2>
<p>Wait 3 seconds (3000 milliseconds) for this page to change.</p>
<h1 id="demo"></h1>
<script>
setTimeout(function() { myFunction("I love You !!!"); }, 3000);
function myFunction(value) {
[Link]("demo").innerHTML = value;
}
</script>
</body>
</html>
Output (After 3 seconds):
JavaScript Functions
setTimeout() with a Callback
Wait 3 seconds (3000 milliseconds) for this page to change.
I love Nodejs !!
8
setInterval()
When using this JavaScript function, you can specify a callback function
to be executed for each interval:
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Functions</h1>
<h2>setInterval() with a Callback</h2>
<p>Using setInterval() to display the time every second (1000 milliseconds).</p>
<h1 id="demo"></h1>
<script>
setInterval(myFunction, 1000);
function myFunction() {
let d = new Date();
[Link]("demo").innerHTML=
[Link]() + ":" +
[Link]() + ":" +
[Link]();
}
</script>
Oputput:
JavaScript Functions
setInterval() with a Callback
Using setInterval() to display the time every second (1000 milliseconds).
[Link] → update every second, like a real-time clock.