A callback function can return a value, in other words, but the code that calls the function won't pay attention to the return value. Yes, it makes fun sense to try and return a value from a promise callback.
Return statements are used to indicates the end of a given function's execution whereas callbacks are used to indicate the desired end of a given function's execution.
Callbacks make sure that a function is not going to run before a task is completed but will run right after the task has completed. It helps us develop asynchronous JavaScript code and keeps us safe from problems and errors.
A key difference between the two is when using the callback approach, we'd normally just pass a callback into a function that would then get called upon completion in order to get the result of something. In promises, however, you attach callbacks on the returned promise object.
I am curious what is considered the better style/the correct way to do something.
In javascript, I could do the following:
function one() {
two(param, function(ans){
// do more work
});
}
function two(param, callback) {
var answer;
//do work
callback(answer);
}
but I could have a similar result by simply returning the answer:
function one() {
var ans = two(param);
// do more work
}
function two(param, callback) {
var answer;
//do work
return answer;
}
I think that if all you need is "answer" then it is probably better to use the second version and just return that value rather than passing a callback function as a parameter, etc. - is my thinking correct? Any ideas on the relative performance of the two? Again, I would expect the return version to be better performance-wise.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With