From 0318fe48e3a66e43481c1242bb42e357a06af82a Mon Sep 17 00:00:00 2001 From: Arik Chakma Date: Sat, 23 Sep 2023 16:04:32 +0600 Subject: [PATCH] wip: add more question --- .../javascript/content/callback-hell.md | 48 +++++++++++++++++++ .../question-groups/javascript/javascript.md | 5 ++ 2 files changed, 53 insertions(+) create mode 100644 src/data/question-groups/javascript/content/callback-hell.md diff --git a/src/data/question-groups/javascript/content/callback-hell.md b/src/data/question-groups/javascript/content/callback-hell.md new file mode 100644 index 000000000..bb243b805 --- /dev/null +++ b/src/data/question-groups/javascript/content/callback-hell.md @@ -0,0 +1,48 @@ +**Callback hell**, often referred to as **Pyramid of Doom**, describes a situation in JavaScript where multiple nested callbacks become difficult to manage, leading to unreadable and unmaintainable code. It often arises when performing multiple asynchronous operations that depend on the completion of previous operations. The code starts to take on a pyramidal shape due to the nesting. + +## Example of callback hell + +```js +callAsync1(function () { + callAsync2(function () { + callAsync3(function () { + callAsync4(function () { + callAsync5(function () { + // ... + }); + }); + }); + }); +}); +``` + +## Strategies to avoid callback hell + +Developers can address or avoid callback hell by using strategies like modularizing the code into named functions, using asynchronous control flow libraries, or leveraging modern JavaScript features like Promises and `async/await` to write more linear, readable asynchronous code. + +### Promise chaining + +```js +callAsync1() + .then(() => callAsync2()) + .then(() => callAsync3()) + .then(() => callAsync4()) + .then(() => callAsync5()) + .catch((err) => console.error(err)); +``` + +### Async/await + +```js +async function asyncCall() { + try { + await callAsync1(); + await callAsync2(); + await callAsync3(); + await callAsync4(); + await callAsync5(); + } catch (err) { + console.error(err); + } +} +``` diff --git a/src/data/question-groups/javascript/javascript.md b/src/data/question-groups/javascript/javascript.md index 67b9c7699..9020b673b 100644 --- a/src/data/question-groups/javascript/javascript.md +++ b/src/data/question-groups/javascript/javascript.md @@ -138,4 +138,9 @@ questions: topics: - 'Core' - 'Advanced' + - question: What is callback hell in JavaScript? + answer: callback-hell.md + topics: + - 'Core' + - 'Advanced' ---