Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - return a value or use a callback function

Tags:

People also ask

Can I return value from callback function JavaScript?

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.

What is difference between return and callback in JavaScript functions?

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.

When would you use a callback function?

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.

Should I use callback or promise?

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.