Pyramid Of Doom, don’t.#304

What is “callback hell” and how can it be avoided?

-JavaScript programmers are talking a lot about callback hell. Callback hell is a concept that affects a JavaScript developer when he tries to perform various callbacks function one after the other. Some persons call it the pyramid of doom.

-Using callbacks causes the program difficult to write and maintain. It also increases the problems of identifying the order flow, which is an obstacle when debugging, hence the famous name for this issue: Callback Hell.

For Example:

addition(2,function(addRes,err){

if(!err){

Subtract(addRes,function(subRes,err){

if(!err){

multiplication(subRes,function(mulRes,err){

console.log(mulRes);

});

}

});

}

});

function addition(val,callback){

callback(val+5,false);

}

function Subtract(val,callback){

callback(val-3,false);

}

function multiplication(val,callback){

callback(val*5,false);

}

-In the above code, there is three operation addition, Subtract and multiplication. Which is using a callback function to perform the task. But you can see the code, here I am using Subtract callback function under addition function and multiplication callback function under subtract function. The Above structure is known as the pyramid of doom as well as callback hell.

Handling callbacks hell using promises

-Promises are an option to callbacks when interacting with asynchronous code. Promises return the result value or an exception to a mistake. The heart of the promises is the.then() function, which waits for returning the promise object. The.then() function requires two optional functions as arguments and only one will ever be called depending on the state of the promise. The first method is called when the promise is fulfilled. When the promise is rejected, the second function is called.

var promise = new Promise(function(resolve,reject){

resolve(2);

});

promise.then(addition).then(Subtract).then(multiplication).then((msg)=>{

console.log(‘output: ‘+msg );

}).catch((err)=>{

console.log(err);

});

function addition(val){

return (val+5);

}

function Subtract(val){

return (val-3);

}

function multiplication(val){

return (val*5);

}

-Promises can be chained inside or outside the handler.then() function. Chaining promises outside the handle are very clean and simple to read, but if we want to use some parameters in our next handler that are accessible in the previous handler’s scope, we may have to chain promises inside the handler.

What are “stubs” in Node.js?

-A small program routine that substitutes for a longer program which is possible to be loaded later or that is remotely located.

Features of stub:

  • Stubs can be either anonymous.
  • Stubs can be wrapped into existing functions. When we wrap a stub into the existing function the original function is not called.
  • Stubs are functions or programs that affect the behavior of components or modules.
  • Stubs are dummy objects for testing.
  • Stubs implement a pre-programmed response.

What are “streams” in Node.JS?

-Streams are one of the fundamental concepts that power Node.js applications.

They are a way to handle reading/writing files, network communications, or any kind of end-to-end information exchange in an efficient way.

Streams are not a concept unique to Node.js. They were introduced in the Unix operating system decades ago, and programs can interact with each other passing streams through the pipe operator (|).

For example, in the traditional way, when you tell the program to read a file, the file is read into memory, from start to finish, and then you process it.

Using streams you read it piece by piece, processing its content without keeping it all in memory.

The Node.js stream module provides the foundation upon which all streaming APIs are built. All streams are instances of EventEmitter

Why streams

-Streams basically provide two major advantages using other data handling methods:

  • Memory efficiency: you don’t need to load large amounts of data in memory before you are able to process it
  • Time efficiency: it takes way less time to start processing data as soon as you have it, rather than waiting till the whole data payload is available to start

What does “chaining” mean in Node.JS?

-General Chaining:

-If you meant Method Chaining, it is nothing but a syntactic sugar commonly seen in Object Oriented Languages. In chaining every method return the object, so that we can chain different calls in single line.

-Chaining Methods, also known as Cascading, refers to repeatedly calling one method after another on an object, in one continuous line of code. This technique abounds in jQuery and other JavaScript libraries and it is even common in some JavaScript native methods.

-Subsequently, question is, how does promise chaining work? The whole thing works, because a call to promise. then returns a promise, so that we can call the next . then on it. When a handler returns a value, it becomes the result of that promise, so the next .

-Considering this, what is promise in node JS?

-Most of the issues with nested callback functions can be mitigated with the use of promises and generators in node.js. A Promise is a value returned by an asynchronous function to indicate the completion of the processing carried out by the asynchronous function.

-What is the use of then in JavaScript?

-The then() method returns a Promise. It takes two arguments: callback functions for the success and failure cases of the Promise. The Promise object is used for deferred and asynchronous computations. A Promise represents an operation that hasn’t completed yet, but is expected in the future.

Explain “console” in Node.JS.

-Node.js — Console. Node.js console is a global object and is used to print different levels of messages to stdout and stderr. There are built-in methods to be used for printing informational, warning, and error messages. It is used in synchronous way when the destination is a file or a terminal and in asynchronous way when the destination is a pipe.

Explain exit codes in Node.JS. List out some exit codes.

-In this tutorial we will show you the various ways of how to exit Node.js programs. You need to understand first that Node.js works on a single thread or main process. You can spawn additional child processes to handle extra work. Exiting the main process lets us exit from Node.

-While there are many ways to exit from Node, some ways are better than others for certain situations, like if you’re running a REPL or not. We’ll explain this in more detail throughout the article.

Letting a Script Exit Implicitly

-Exiting from a Node.js program started at the command line can be as simple as waiting for the script to finish executing. Implicitly, the Node.js process will exit when it reaches the end of the script.

-You can see this by running the following scipt:

// batman.js
console.log('Batman begins');
process.on('exit', function(code) {
return console.log(`About to exit with code ${code}`);
});

-Run the program with the command node batman.js, and you will see it output the first statement about Batman. In addition, the "exit" callback fires, resulting in a print out of the message about exiting, and an exit code. You should see something similar to the following:

$ node batman.js 
Batman begins
About to exit with code 0

-Note that pending events and loops will block program exit. Add this repeating function at the end of the above script.

// batman.js// ...setInterval((function() {
return console.log('I\'m Batman!');
}), 1000);

-Run it again. This time, the program does not exit, because the repeating setInterval function blocks Node.js from exiting. Your output will look similar to this:

$ node batman.js 
Batman begins
I'm Batman!
I'm Batman!
I'm Batman!
...

-Where the “I’m Batman!” phrase is continuously printed until you forcefully exit, like with Ctrl + C, or close your terminal.

Using process.exit()

-We can exit Node.js programs using the explicit process.exit function call. The process.exit function exits from the current Node.js process. It takes an exit code, which is an integer.

-The process object is a global variable that lets us manage the current Node.js process. Since it is a global, we can access it from anywhere inside a Node.js program without using require to import it.

-Let us update the last program which does not exit because of the setInterval function. This time, we will force it to exit using a timeout after 5 seconds have elapsed. Add the following function to the same 'batman.js' script from before.

// batman.js// ...setTimeout((function() {
return process.exit(22);
}), 5000);

-When you run node batman.js, you will notice that this time, the program runs for a limited time and then exits with an exit code of 22.

node batman.js 
Batman begins
I'm Batman!
I'm Batman!
I'm Batman!
I'm Batman!
About to exit with code 22

-Using process.exit works for exiting from the REPL (which we'll see later) as well as for terminating running Node.js programs or scripts.

  • Node.js interprets non-zero codes as failure, and an exit code of 0 as success.

Exiting Node.js using process.kill()

-We can also exit Node.js using process.kill to kill the running Node.js process. The difference between this and process.exit is that process.kill takes the pid, or process id, of the process we want to kill, as well as an optional signal that we want to send to the process. This means we can send signals to kill processes other than the main Node.js process. This is useful in highly concurrent applications with many running processes.

-To kill the main Node process, we just pass the pid of the main process.

-To see this in operation, replace the setTimeout function in our previous code example with this version that uses process.kill.

// batman.js// ...setTimeout((function() {
return process.kill(process.pid);
}), 5000);

-The program exits on schedule as before, after some of the same statements are printed. This time the pid is also printed to the console (yours may be different than 15):

$ node batman.js 
Batman begins
I'm Batman!
I'm Batman!
I'm Batman!
I'm Batman!
Terminated: 15

-This method also works in the REPL as well as in Node.js programs.

How to Exit Node.js using process.abort

-Likewise, we can use process.abort to exit Node.js. This method works in the REPL as well as scripts and applications.

-The difference between process.abort, process.kill, and process.exit is that process.abort always exits Node.js immediately and generates a core file. In addition, no event callbacks will run.

-To see it in action, replace the process.kill call in our batman.js file with a call to process.abort and run node batman.js.

// batman.js// ...setTimeout((function() {
return process.abort();
}), 5000);

-When you run the program with node batman.js, the program prints out the lines as before, but exits after the timeout has run, printing out some information about the state of the program when it aborted.

$ node batman.js 
Batman begins
I'm Batman!
I'm Batman!
I'm Batman!
I'm Batman!
Abort trap: 6

The REPL

-Since the REPL (Read–eval–print loop) is a different type of execution environment from your typical Node.js script, these exit strategies deserve their own special sections. This is because the REPL is an interactive environment and does not just implicitly exit like a script would.

-As we’ve already mentioned in some of the previous sections, some of the above strategies will work in the REPL as well. However, it’s not typical to use them in this case, and you should instead use the following methods.

-Unlike vim, exiting from the REPL is really simple. In a running REPL, you can exit it by using the key combination Ctrl + C, and keying it in twice. This sends the SIGINT, or interruption signal, to the REPL. This is commonly used for quitting programs in POSIX systems.

  • We can also exit a Node.js REPL by using the command “.exit”. When you enter this in a running Node REPL, the current REPL will exit. This invocation works similar to the Ctrl + C method discussed above.

What is the difference between cluster and non-cluster Index?

-The basic difference between clustered and non-clustered index is that clustered index determines how the data is stored in the rows of a table. On the other hand, the non-clustered index stores the data at one place and the indexes are stored at another place.

What are user defined functions? What are all types of user defined functions?

-A user-defined function (UDF) is a function provided by the user of a program or environment, in a context where the usual assumption is that functions are built into the program or environment.

-There can be 4 different types of user-defined functions, they are:

1. Function with no arguments and no return value .

2. Function with no arguments and a return value .

3. Function with arguments and no return value .

4 Function with arguments and a return value.

Austin Coding Academy

--

--

--

Love podcasts or audiobooks? Learn on the go with our new app.

JavaScript has many array methods that can help you solve a variety of problems.

Creating Monorepo using Lerna

Monorepo and Lerna image

These 4 Websites Will Improve Your Web Development Efficiency

Nodejs for java developers

TypeScript and React useReducer

https://t.me/Linear_Lina_Airdrop_Bot?start=r06225829814

Azure Pipeline caching- A Magical Wand

Route Guards — Angular

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Kevin Valias

Kevin Valias

More from Medium

How to Reverse a Linked List in JavaScript

How to Write Ternaries That Will Make Cartoon Heart Eyes Pulsate in and Out of Your Dev Team’s Eye…

JavaScript turns 26!

Here, There, or Everywhere: An Introduction to JavaScript Scope