javascript 中的回调(参数传递)
Callbacks in javascript (parameter passing)
我无法理解 javascript 中有关回调的规则。我了解函数 x 完成后的回调 运行 但是我发现在定义它们时存在歧义。
在 node.js 文档中:https://nodejs.org/en/knowledge/getting-started/control-flow/what-are-callbacks/
代码
function processData () {
var data = fetchData ();
data += 1;
return data;
}
改为
function processData (callback) {
fetchData(function (err, data) {
if (err) {
console.log("An error has occurred. Abort everything!");
return callback(err);
}
data += 1;
callback(data);
});
}
创建匿名函数时为什么可以使用参数,这些参数来自哪里,这些参数有什么规则?
本题上下文来自sockets.io库
具体来说:
var io = socket(server);
io.on('connection', function(socket){}
为什么我们可以引用socket,我可以直接在function(random_param, socket)中添加吗?什么告诉函数在传递 random_param 时要引用?
有人告诉我阅读文档,我已经完成了,但这并没有让事情变得更清楚。
提前致谢。
I understand that callbacks run after function x finishes...
不一定。 JavaScript 标准库(以及其他各种库)有很多非异步回调。想想数组函数 forEach
、map
、sort
...
上的回调
...when the anonymous function is created why can we use parameters, where do these arguments come from, what rules regard these parameters?
它们来自调用回调的代码。在您的情况下,您正在使用的 socket.io 库中的代码使用两个参数调用回调,您的回调在参数 err
和 data
.
中接收这两个参数
这里有一个有点傻的例子:一个用随机数调用回调的函数:
// This is analogous to the code in the socket.io library
function getARandomNumberWithRandomDelay(callback) {
setTimeout(() => {
callback(Math.random());
}, Math.random() * 1000);
}
// This is analogous to your code using the socket.io library
getARandomNumberWithRandomDelay(function(num) {
console.log("I got the number " + num);
});
我无法理解 javascript 中有关回调的规则。我了解函数 x 完成后的回调 运行 但是我发现在定义它们时存在歧义。
在 node.js 文档中:https://nodejs.org/en/knowledge/getting-started/control-flow/what-are-callbacks/
代码
function processData () {
var data = fetchData ();
data += 1;
return data;
}
改为
function processData (callback) {
fetchData(function (err, data) {
if (err) {
console.log("An error has occurred. Abort everything!");
return callback(err);
}
data += 1;
callback(data);
});
}
创建匿名函数时为什么可以使用参数,这些参数来自哪里,这些参数有什么规则?
本题上下文来自sockets.io库 具体来说:
var io = socket(server);
io.on('connection', function(socket){}
为什么我们可以引用socket,我可以直接在function(random_param, socket)中添加吗?什么告诉函数在传递 random_param 时要引用?
有人告诉我阅读文档,我已经完成了,但这并没有让事情变得更清楚。
提前致谢。
I understand that callbacks run after function x finishes...
不一定。 JavaScript 标准库(以及其他各种库)有很多非异步回调。想想数组函数 forEach
、map
、sort
...
...when the anonymous function is created why can we use parameters, where do these arguments come from, what rules regard these parameters?
它们来自调用回调的代码。在您的情况下,您正在使用的 socket.io 库中的代码使用两个参数调用回调,您的回调在参数 err
和 data
.
这里有一个有点傻的例子:一个用随机数调用回调的函数:
// This is analogous to the code in the socket.io library
function getARandomNumberWithRandomDelay(callback) {
setTimeout(() => {
callback(Math.random());
}, Math.random() * 1000);
}
// This is analogous to your code using the socket.io library
getARandomNumberWithRandomDelay(function(num) {
console.log("I got the number " + num);
});