Reputation: 1631
for example I have a function A that has to return some value
function A(callback){
//some computation
var fakeData = 20;
callback(null,fakeData)
}
function B(err,data){
if(!err){
console.log(data);
}
}
A(B);
so as far as I know only I/O operations in node js runs asynchronously, so whats the difference if I right just this
function A(){
var fakeData = 20;
return fakeData;
}
function B(data){
console.log(data);
}
var data = A();
B(data);
I mean both of them will run synchronously right?
Upvotes: 1
Views: 87
Reputation: 1520
If you are talking about these two functions then yes these two are identical but this is not the use of callbacks as callbacks are used when you have a process which returns the result after some time or in the future like a database call or a rest api call or a file read/write operations for which we are not sure about when did they returns the result.
Upvotes: 0
Reputation: 707318
The callback pattern is useful for a number of types of problems:
When your function uses asynchronous operations and you want to be able to notify the caller when the asynchronous operations are complete and perhaps pass a final result to the caller.
When your function wants the caller to supply some function that can be used in the computation of a result as in the callback that can be passed to array.sort(callback)
.
You would generally NOT use a callback pattern to communicate the result of a synchronous operation because that just makes the code more complicated than just directly returning the result from the function. So, if all your operations in A()
are synchronous, then your second code option will be simpler to code and use.
Upvotes: 1