javascript - Why does this callback return undefined? - Stack Overflow

function firstFunction(num, callback) {callback(num);};function secondFunction(num) {return num + 99;

function firstFunction(num, callback) {
  callback(num);
};

function secondFunction(num) {
  return num + 99;
};

console.log(firstFunction(56, secondFunction));
undefined

If I call console.log from within secondFunction, it returns the value.

Why not? What's the point of setting up callbacks if I can't get the value out of them to use later? I'm missing something.

function firstFunction(num, callback) {
  callback(num);
};

function secondFunction(num) {
  return num + 99;
};

console.log(firstFunction(56, secondFunction));
undefined

If I call console.log from within secondFunction, it returns the value.

Why not? What's the point of setting up callbacks if I can't get the value out of them to use later? I'm missing something.

Share Improve this question edited May 25, 2013 at 2:53 tckmn 59.4k27 gold badges118 silver badges156 bronze badges asked May 25, 2013 at 2:47 dsp_099dsp_099 6,13120 gold badges78 silver badges132 bronze badges 1
  • 2 You forgot the chain the return value from callback. – Ja͢ck Commented May 25, 2013 at 2:50
Add a ment  | 

2 Answers 2

Reset to default 8

In your function firstFunction, you do:

callback(num);

Which evaluates to

56 + 99;

Which is then

155;

But you never return the value! Without a return value, a function will simply evaluate to undefined.


Try doing this:

function firstFunction(num, callback) {
  return callback(num);
};

firstFunction does not return anything, plain and simple! That is why when you console.log the return value, it is undefined.

The code in question:

callback(num);

calls callback and then does nothing with the returned value. You want:

return callback(num);

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1743723627a4496245.html

相关推荐

  • javascript - Why does this callback return undefined? - Stack Overflow

    function firstFunction(num, callback) {callback(num);};function secondFunction(num) {return num + 99;

    6天前
    10

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信