Javascript node js callback() 函数未定义?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34034663/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 15:49:42  来源:igfitidea点击:

node js callback() function is not defined?

javascriptnode.jscallback

提问by Tao Qin

Hello I am new to node js and I am trying to write a simple callback function however get "ReferenceError: sum1 is not defined", can anyone help me? code:

您好,我是 node js 的新手,我正在尝试编写一个简单的回调函数,但是得到“ReferenceError: sum1 is not defined”,有人可以帮我吗?代码:

sum1(1,2, function(sum){
  console.log(3 + sum);
});
sum1 = function (a,b, callback){
  callback(a + b);
};

However, I tried to use function sum1(a,b,callback){...}and it works. Is this a naming problem? Can anyone explain a little bit?

但是,我尝试使用 function sum1(a,b,callback){...}并且它有效。这是命名问题吗?谁能解释一下?

回答by jfriend00

You have to define the function before you call it. When you use the form:

您必须在调用之前定义该函数。当您使用表格时:

sum1 = function() {...} 

to define your function, that definition MUST occur BEFORE you use the function. That's because the function is not assigned to the sum1variable until that line of code executes. So, if you try to execute sum1(...)before that line runs, then sum1is not yet defined and you get the exception.

要定义您的函数,该定义必须在您使用该函数之前发生。那是因为在sum1该行代码执行之前,函数不会分配给变量。因此,如果您尝试sum1(...)在该行运行之前执行,则sum1尚未定义并且您会收到异常。

If you use the form:

如果您使用表格:

function sum1() {...}

Then, the symbol sum1is defined at parse time BEFORE any code executes so the order of placement in the file is not an issue.

然后,sum1在任何代码执行之前的解析时间定义符号,因此文件中的放置顺序不是问题。

回答by TbWill4321

You have to define sum1prior to calling it, or use a function declaration:

您必须sum1在调用之前定义,或使用函数声明:

// Define first:
var sum1 = function (a,b, callback){
    callback(a + b);
};
sum1(1, 2, function(sum) {
    console.log(3 + sum);
});

Or

或者

// Function Declaration:
sum1(1, 2, function(sum) {
    console.log(3 + sum);
});
function sum1(a,b, callback){
    callback(a + b);
};

Function declarations can be after the code calling it. However, for clarity's sake, you should always define a function (either way) before you use it in your code.

函数声明可以在调用它的代码之后。但是,为了清楚起见,在您的代码中使用函数之前,您应该始终定义它(无论哪种方式)。

回答by Ramanlfc

sum1 = function (a,b, callback){
  callback(a + b);
};

This is a function expression , so you can't call sum1()before it's definition , move it above the function call.

这是一个函数表达式,所以你不能sum1()在它定义之前调用,把它移到函数调用之上。