最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Is "return;" necessaryhelpful when using callbacks in Node.JS? - Stack Overflow

programmeradmin5浏览0评论

For example, are these two effectively the same?

someFunction(val, callback){
    callback(val);
};

and

someFunction(val, callback){
    callback(val);
    return;  // necessary?
};

For example, are these two effectively the same?

someFunction(val, callback){
    callback(val);
};

and

someFunction(val, callback){
    callback(val);
    return;  // necessary?
};
Share Improve this question edited Mar 1, 2012 at 0:15 randylubin asked Feb 29, 2012 at 23:10 randylubinrandylubin 551 silver badge5 bronze badges 1
  • 1 Note that you can't use the name "var" as a function parameter name since "var" is a keyword (which declares variables)! You should modify your question and change "var" to "val", or something else to avoid nit picking in the answers =) – maerics Commented Feb 29, 2012 at 23:18
Add a ment  | 

5 Answers 5

Reset to default 9

While they are the same, you will see something like the following from time to time:

someFunction(val, callback){
  if (typeof val != 'object')
    return callback(new Error('val must be an object'));
  callback(null, val);
};

In other words, return is used to "break" out of the function early. Most often, I've seen that used with conditionals; you test for an error condition (returning the callback early if there is an error), then avoid having to wrap the remainder of the function in an else clause.

Yes, they are the same. If your function does not return a value then you can either omit the return statement or use it with no argument; in both cases a call to the function returns "undefined".

function f1(){};
typeof(f1()); // => "undefined"

function f2(){return;};
typeof(f2()); // => "undefined"

In a general JavaScript sense, yes, they're the same - I don't see why node.js would be any different.

In both cases the return value from someFunction() will be undefined. Whether or not there's a callback within the function is irrelevant.

Beside the fact that you cannot have a formal parameter named var your two snippets are identical and working the same way. Every function in ECMAscript implicity returns undefined if not specified.

They are the same; you should not use return, because putting it there will be confusing to readers since it is unnecessary.

sidenote: In some languages (but probably not javascript) that return statement might not even be executed if tail-call optimizations are enabled (that is, it is reasonable for the piler to remove the function from the stack once you leave it if you never plan to do anything else). Once again, probably not relevant in any implementation of standard javascript.

发布评论

评论列表(0)

  1. 暂无评论