NodeJS - sakib03/Interview GitHub Wiki
Important Links
How to Build a RESTful API Using Node, Express, and MongoDB
Common Question
Event Loop
Middleware
We will call a unique parameter at single place and use in every API call (app.use(middlewareFunction()))
Middleware functions can perform the following tasks:
- Execute any code.
- Make changes to the request and the response objects.
Why we should use NodeJS
Where we should not use NodeJS
Callback and callback hell and how to resolve it
Callback: Callback function is a function that is usually pass as an argument to another function that actually invoked after some kind of an event. A callback is a function called at the completion of a given task; this prevents any blocking, and allows other code to be run in the meantime. Is used when async function has done his job and is ready to present data, If we want to wait for something in JavaScript, we need to use a callback.
Callback hell: When output of one async function is input to next async function inside nested callbacks or scenarios which results in code unmanageable and unreadable which finds hard to find error.
There are four solutions to callback hell:
- Write comments.
- Split functions into smaller functions.
- Using Promises.
- Using Async/await.
A promise is an object that will return a value in future. Because of this “in future” thing, Promises are well suited for asynchronous JavaScript operations.
Converting callbacks to promises:
To convert callbacks into promises, we need to create a new promise for each callback. We can resolve the promise when the callback is successful. Or we can reject the promise if the callback fails.