Callbacks क्या हैं
एक callback एक function है जिसे आप दूसरे function को देते हैं ताकि काम खत्म होने पर इसे बाद में call किया जाए।
In this page:
Syntax
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
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. #}
आम गलतियां
- error argument ignore करना
- एक callback दो बार call करना
- 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: