9

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.

3 Answers 3

10

Generally a callback function is used when the function you are calling will be performing an asynchronous event (such as making an AJAX call) that will be done in a non-blocking fashion.

Non-blocking means that once you call that function, your code will continue on to the next statement BEFORE the function you just called has completed its work. Hence the callback function, in which you put code that you want to be executed AFTER the non-blocking function has completed.

I would recommend returning answer directly from two rather then implementing a callback. Too many callbacks can lead to what is known as the Callback Pyramid

Sign up to request clarification or add additional context in comments.

2 Comments

I was curious just in general, but the situation that brought it up does have to do with asynchronous events. I had forgotten about this - thank you for a great explanation.
link is broken!
5

You should use the return.

Callback are suitable when you perform asynchronous actions, otherwise they're useless overhead.

2 Comments

I would argue they have uses outside of asynchronous actions, for instance if you create your own library or plugin, it can be useful to allow users to pass in a function they want to execute after some event.
Yeah, events are asynchronous. Though I admit this could've been clearer.
1

You should definitely just use return. Callbacks are meant for when you would like some customized code to be executed after the completion of a function or an asynchronous event such as an Ajax call.

2 Comments

If the function is not async, you only add the code to execute after the call expression IMO
@SimonBoudrias See my comment on your post. What about callbacks specified in libraries like jQueryUI?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.