← Back to Node.js Course | Chapter 4: Async Programming | Lesson 1 of 7

Callbacks क्या हैं

एक callback एक function है जिसे आप दूसरे function को देते हैं ताकि काम खत्म होने पर इसे बाद में call किया जाए।

In this page:

  1. Callbacks
Syntax
javascript
function functionName(args, callback) {
  // do work
  callback(err, result);
}

functionName(args, (err, result) => {
  if (err) return handleError(err);
  // use result
});

Callbacks

Node की classic style error-first callbacks है: पहला argument एक error या null है, results के बाद आते हुए। Callbacks का deep nesting hard-to-read callback hell की ओर ले जाता है, जिसे promises और async/await solve करते हैं।

Note: हमेशा err argument पहले check करें।

उदाहरण: Callbacks

javascript
function getUser(id, cb) {
  setTimeout(() => {
    if (id <= 0) return cb(new Error("bad id"));
    cb(null, { id, name: "Ada" });
  }, 5);
}
getUser(1, (err, user) => console.log(err ? err.message : user));
getUser(0, (err, user) => console.log(err ? err.message : user));

// Output:
// { id: 1, name: 'Ada' }
// bad id

⚠️ Run this in your own terminal or Node.js environment.

Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. error argument ignore करना
  2. एक callback दो बार call करना
  3. async callbacks के अंदर throw करना और process crash करना
चैप्टर सारांश
  • काम complete होने पर Callbacks चलते हैं
  • Error-first convention इस्तेमाल होता है
  • Nesting callback hell cause करता है
  • हमेशा err handle करें
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.