Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is cb() in Node?

Tags:

Where are people getting cb() from, is this a Node thing or vanilla JS thing?

For example:

Managing Node.js Callback Hell with Promises, Generators and Other Approaches

they're using cb() to I guess callback and return an error or a value or both in some cases depending on what the callback function sig is?

like image 356
PositiveGuy Avatar asked Aug 03 '15 06:08

PositiveGuy


People also ask

What does CB mean for JavaScript?

cb stands for callback, nothing special, just avariable name, can be replaced by any other variable name.

What does CB mean in multer?

cb is a callback function that accepts 2 parameters.

What is callback function and how it works?

A callback function is a function that is passed as an argument to another function, to be “called back” at a later time. A function that accepts other functions as arguments is called a higher-order function, which contains the logic for when the callback function gets executed.

What is callback function in node?

What is Callback? Callback is an asynchronous equivalent for a function. A callback function is called at the completion of a given task. Node makes heavy use of callbacks. All the APIs of Node are written in such a way that they support callbacks.


1 Answers

cb in the context you're describing it is how a vanilla callback function is passed into a (typically) asynchronous function, which is a common pattern in node.js (it's sometimes labelled next, but you can call it bananas if you so desire - it's just an argument).

Typically the first argument is an error object (often false - if all went as planned) and subsequent arguments are data of some form.

For example:

function myAsyncFunction(arg1, arg2, cb) {     // async things     cb(false, { data: 123 }); } 

then using this function:

myAsyncFunction(10, 99, function onComplete(error, data) {     if (!error) {         // hooray, everything went as planned     } else {         // disaster - retry / respond with an error etc     } }); 

Promises are an alternative to this design pattern where you would return a Promise object from myAsyncFunction

For example:

function myAsyncFunction2(arg1, arg2) {     return new Promise(function resolution(resolve, reject, {         // async things         resolve({ data: 123 });     }); } 

then using this function:

myAsyncFunction2(10, 99)     .then(function onSuccess(data) {         // success - send a 200 code etc     })     .catch(function onError(error) {         // oh noes - 500     }); 

They're basically the same thing, just written slightly differently. Promises aren't supported especially widely in a native form, but if put through a transpiler (I'd recommend babel) during a build step they should perform reliably enough in a browser too.

Callbacks will always work in a browser with no shimming / transpilation.

like image 134
Joshua Avatar answered Oct 01 '22 23:10

Joshua