1564042437
Callbacks are one of the critical elements to understand JavaScript and Node.js. Nearly, all the asynchronous functions use a callback (or promises). In this post, we are going to cover callbacks in-depth and best practices.
This post assumes you know the difference between synchronous and asynchronous code.
JavaScript is an event-driven language. Instead of waiting for things to happen, it executes while listening for events. The way you respond to an event is using callbacks.
A callback is a function that is passed as an argument to another function.
Callbacks are also known as higher-order function.
An example of a callback is the following:
const compute = (n1, n2, callback) => callback(n1, n2);
const sum = (n1, n2) => n1 + n2;
const product = (n1, n2) => n1 * n2;
console.log(compute(5, 3, sum)); // ↪️ 8
console.log(compute(5, 3, product)); // ↪️ 15
As you can see the function compute
takes two numbers and a callback function. This callback
function can be sum
, product
and any other that you develop that operates two numbers.
Callbacks can help to make your code more maintainable if you use them well. They will also help you to:
compute
that can handle all sorts of functionalities (e.g., sum
, product
)So far, we have only seen callbacks that are executed immediately; however, most of the callbacks in JavaScript are tied to an event like a timer, API request or reading a file.
An asynchronous callback is a function that is passed as an argument to another function and gets invoke zero or multiple times after certain events happens.
It’s like when your friends tell you to call them back when you arrive at the restaurant. You coming to the restaurant is the “event” that triggers the callback. Something similar happens in the programming world. The event could be you click a button, a file is loaded into memory, and request to a server API, and so on.
Let’s see an example with two callbacks:
const id = setInterval(() => console.log('tick ⏰'), 1e3);
setTimeout(() => clearInterval(id), 5e3);
First, you notice that we are using anonymous functions (in the previous example, we were passing the named functions such as sum
and product
). The callback passed to setInterval
is triggered every second, and it prints tick
. The second callback is called one after 5 seconds. It cancels the interval, so it just writes tick
five times.
Callbacks are a way to make sure a particular code doesn’t execute until another has already finished.
Theconsole.log('tick')
only gets executed when a second has passed.
The functions setInterval
and setTimeout
callbacks are very simple. They don’t provide any parameters on the callback functions. But, if we are reading from the file system or network, we can get the response as a callback parameter.
The callback parameters allow you to get messages into your functions when they are available. Let’s say we are going to create a vanilla server on Node.js.
const http = require('http');
const port = 1777;
const host = '127.0.0.1';
const proxy = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end(`Hello World from Node! You used url "${req.url}"\r\n`);
});
proxy.listen(port, host, () => {
console.log(`Server running on http://${host}:${port}`);
});
We have two callbacks here. The http.createServer
‘s callback sends the parameters (req
)uest and (res
)ponse every time somebody connects to the server.
You can test this server using curl (or browser)
curl 127.0.0.1:1777/this/is/cool
There you have it! An HTTP server that replies to everyone that connects to it using a callback. But, What would happen if there’s an error? Let’s see how to handle that next.
Some callbacks send errors on the first parameter and then the data (callback(error, data)
). That’s very common in Node.js API. Let’s say we want to see all the directories on a given folder:
const fs = require('fs');
fs.readdir('/Users/adrian/Code', (error, files) => {
if (error) { console.error(error); }
console.log(files);
});
As you notice, the first parameter will have an error message. If you run it, you would probably have the error message (unless you have the same name and directory).
{ [Error: ENOENT: no such file or directory, scandir '/Users/noAdrian/Code']
errno: -2,
code: 'ENOENT',
syscall: 'scandir',
path: '/Users/noAdrian/Code' }
undefined
So that’s how you handle errors, you check for that parameter. But (there’s always a but) what if I need to do multiple async operations. The easiest way (but not the best) is to have a callback inside a callback:
const fs = require('fs');
const dir = '/Users/adrian/Code';
function printFilesSize(basePath) {
fs.readdir(basePath, (err, files) => {
if (err) {
console.log(`Error finding files: ${err}`);
} else {
files.forEach((filename) => {
const filePath = `${basePath}/${filename}`;
fs.lstat(filePath, (err, stat) => {
if (err) { console.error(err); }
if (stat.isFile()) {
console.log(filePath, stat.size.toLocaleString());
}
});
});
}
});
}
printFilesSize(dir);
As you can see, this program will first read files in a directory and then check the file size of each file, and if it’s a directory, it will be omitted.
When callbacks are nested too many levels deep, we call this callback hell! 🔥 Or the pyramid of doom ⚠️
Because they are hard to maintain, how do we fix the callback hell? Read on!
Callback hell is when you have too many nested callbacks.
a(() => {
b(() => {
c(() => {
d();
});
});
});
To make your code better, you should:
Let’s fix the callback hell from printFilesSize
keeping our code shallow and modularizing it.
const fs = require('fs');
const dir = '/Users/adrian/Code';
function printFileSize(filePath) {
fs.lstat(filePath, (err, stat) => {
if (err) { console.error(err); }
if (stat.isFile()) {
console.log(filePath, stat.size.toLocaleString());
}
});
}
function printFilesSize(files, basePath) {
files.forEach((filename) => {
const filePath = `${basePath}/${filename}`;
printFileSize(filePath);
});
}
function printFilesSizeFromDirectory(basePath) {
fs.readdir(basePath, (err, files) => {
if (err) {
console.log(`Error finding files: ${err}`);
} else {
printFilesSize(files, basePath);
}
});
}
printFilesSizeFromDirectory(dir);
The original implement had five levels of indentation, now that we modularized it is 1-2 levels.
Callbacks are not the only way to deal with asynchronous code. In the following post we are going to cover:
Stay tuned!
Originally published by Adrian Mejia at adrianmejia.com
#javascript #node-js #web-development
1616670795
It is said that a digital resource a business has must be interactive in nature, so the website or the business app should be interactive. How do you make the app interactive? With the use of JavaScript.
Does your business need an interactive website or app?
Hire Dedicated JavaScript Developer from WebClues Infotech as the developer we offer is highly skilled and expert in what they do. Our developers are collaborative in nature and work with complete transparency with the customers.
The technology used to develop the overall app by the developers from WebClues Infotech is at par with the latest available technology.
Get your business app with JavaScript
For more inquiry click here https://bit.ly/31eZyDZ
Book Free Interview: https://bit.ly/3dDShFg
#hire dedicated javascript developers #hire javascript developers #top javascript developers for hire #hire javascript developer #hire a freelancer for javascript developer #hire the best javascript developers
1589255577
As a JavaScript developer of any level, you need to understand its foundational concepts and some of the new ideas that help us developing code. In this article, we are going to review 16 basic concepts. So without further ado, let’s get to it.
#javascript-interview #javascript-development #javascript-fundamental #javascript #javascript-tips
1595553079
During my journey of learning JavaScript and a few days in with React, I had to come to terms with callback functions. It was impossible to avoid its existence and blindly using it without understanding. To understand callback function we have to know a bit about functions. Here I want to talk about function expression, arrow function, and callback function.
According to MDN doc:
A callback function is a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of routine or action.
In JavaScript, functions are objects, which means, like any other objects it can be assigned to a variable and passed as an argument to another function. In a nutshell, a callback function is a function that is provided as a parameter for other methods such as forEach method or addEventListener method and gets invoked at a certain point in time.
So how do we do this? Let’s see with an example below:
document.addEventListener(‘click’,whoAmI);
//whoAmI Function Declaration(Function Statement)
function whoAmI(event){
console.log(event.target.tagName)
}
We attached the ‘click’ event listener to document with whoAmI
function as a parameter that logs the tag name of the clicked target. Whenever ‘click’ happens whoAmI
function will be called with an _event_
argument. We call whoAmI
a callback function.
When we call a function by its name followed by ( ), we are telling the function to execute its code. When we name a function or pass a function without the ( ), the function does not execute.** The callback function doesn’t execute right away. Instead, the addEventListener method executes the function when the event occurs.**
One more thing I want to mention is because we used function declaration, we were able to call thewhoAmI
function before it was declared. It’s the magic of hoisting in JS. But with function expression, it doesn’t get hoisted. So the order of writing function expressions and using them as callback would be crucial.
#callback #javascript #callback-function #function #javascript-fundamental
1622207074
Who invented JavaScript, how it works, as we have given information about Programming language in our previous article ( What is PHP ), but today we will talk about what is JavaScript, why JavaScript is used The Answers to all such questions and much other information about JavaScript, you are going to get here today. Hope this information will work for you.
JavaScript language was invented by Brendan Eich in 1995. JavaScript is inspired by Java Programming Language. The first name of JavaScript was Mocha which was named by Marc Andreessen, Marc Andreessen is the founder of Netscape and in the same year Mocha was renamed LiveScript, and later in December 1995, it was renamed JavaScript which is still in trend.
JavaScript is a client-side scripting language used with HTML (Hypertext Markup Language). JavaScript is an Interpreted / Oriented language called JS in programming language JavaScript code can be run on any normal web browser. To run the code of JavaScript, we have to enable JavaScript of Web Browser. But some web browsers already have JavaScript enabled.
Today almost all websites are using it as web technology, mind is that there is maximum scope in JavaScript in the coming time, so if you want to become a programmer, then you can be very beneficial to learn JavaScript.
In JavaScript, ‘document.write‘ is used to represent a string on a browser.
<script type="text/javascript">
document.write("Hello World!");
</script>
<script type="text/javascript">
//single line comment
/* document.write("Hello"); */
</script>
#javascript #javascript code #javascript hello world #what is javascript #who invented javascript
1626321063
PixelCrayons: Our JavaScript web development service offers you a feature-packed & dynamic web application that effectively caters to your business challenges and provide you the best RoI. Our JavaScript web development company works on all major frameworks & libraries like Angular, React, Nodejs, Vue.js, to name a few.
With 15+ years of domain expertise, we have successfully delivered 13800+ projects and have successfully garnered 6800+ happy customers with 97%+ client retention rate.
Looking for professional JavaScript web app development services? We provide custom JavaScript development services applying latest version frameworks and libraries to propel businesses to the next level. Our well-defined and manageable JS development processes are balanced between cost, time and quality along with clear communication.
Our JavaScript development companies offers you strict NDA, 100% money back guarantee and agile/DevOps approach.
#javascript development company #javascript development services #javascript web development #javascript development #javascript web development services #javascript web development company