简体   繁体   English

Javascript - 返回值或使用回调函数

[英]Javascript - return a value or use a callback function

I am curious what is considered the better style/the correct way to do something. 我很好奇什么被认为是更好的风格/正确的做事方式。

In javascript, I could do the following: 在javascript中,我可以执行以下操作:

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. 同样,我希望返回版本在性能方面更好。

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. 通常,当您调用的函数将执行将以非阻塞方式执行的异步事件(例如进行AJAX调用)时,将使用回调函数。

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. 我建议直接从two answer ,而不是实现一个回调。 Too many callbacks can lead to what is known as the Callback Pyramid 太多的回调可能会导致所谓的回调金字塔

You should use the return. 你应该使用回报。

Callback are suitable when you perform asynchronous actions, otherwise they're useless overhead. 执行异步操作时回调是合适的,否则它们是无用的开销。

You should definitely just use return. 你绝对应该使用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. 回调适用于您希望在完成函数或异步事件(如Ajax调用)后执行某些自定义代码的情况。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM