ganqqwerty / 123-Essential-JavaScript-Interview-Questions

JavaScript interview Questions
BSD 3-Clause "New" or "Revised" License
5.01k stars 1.18k forks source link

added 48th ques about callbackhell promise async/await #109

Closed Kalon1997 closed 3 months ago

Kalon1997 commented 2 years ago

How to replace callbackhell code with Promise or Async / Await in Javascript.

HsDesigner786 commented 1 year ago

Callback hell is a situation in JavaScript where multiple asynchronous operations are nested within one another using callbacks, leading to deeply nested and hard-to-read code. To replace callback hell with Promises or async/await, you can use a more structured and readable approach.

Promises provide a cleaner solution by encapsulating asynchronous operations and allowing you to chain them using .then(). Each asynchronous operation can return a Promise, simplifying the code's structure and making it more manageable. Error handling is achieved through the .catch() method.

On the other hand, async/await is a modern syntax built on top of Promises. It allows you to write asynchronous code that looks more synchronous. By marking a function as async, you can use the await keyword to pause execution until a Promise is resolved or rejected, making the code appear more linear and readable. Error handling can be done using a try-catch block.

By utilizing Promises or async/await, you can transform callback hell into a more organized and maintainable code structure. This improves code readability, makes debugging easier, and enhances overall code quality. It allows you to handle asynchronous operations in a more elegant and sequential manner, leading to more efficient and maintainable JavaScript code.

ganqqwerty commented 3 months ago

good question