1. What is the difference between synchronous and asynchronous functions?
JavaScript is a synchronous, blocking, single-threaded language. That just means that only one operation can be in progress at a time.
Asynchronous callbacks allow you to invoke a callback function which sends a database request (and any other nested callbacks) off to your app, where it waits for a response from the database, freeing up the rest of your code to continue running.
2. What is callback hell?
The cause of callback hell is when people try to write JavaScript in a way where execution happens visually from top to bottom.
Callbacks are just the name of a convention for using JavaScript functions. There isnât a special thing called a âcallbackâ in the JavaScript language, itâs just a convention. Instead of immediately returning some result like most functions, functions that use callbacks take some time to produce a result. The word âasynchronousâ, aka âasyncâ just means âtakes some timeâ or âhappens in the future, not right nowâ. Usually callbacks are only used when doing I/O, e.g. downloading things, reading files, talking to databases, etc.
However, functions that are async and use callbacks donât return anything right away.
3. Which technique can help us solve callback hell?
- Donât nest functions. Give them names and place them at the top level of your program
- Use function hoisting to your advantage to move functions âbelow the foldâ
- Handle every single error in every one of your callbacks. Use a linter like standard to help you with this.
- Create reusable functions and place them in a module to reduce the cognitive load required to understand your code. Splitting your code into small pieces like this also helps you handle errors, write tests, forces you to create a stable and documented public API for your code, and helps with refactoring.