我在理解有关JavaScript回调的规则时遇到了麻烦。我知道回调在函数x完成后运行,但是我发现定义它们时存在歧义。
In the node.js docs : 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){}
为什么我们可以引用套接字,我可以只添加函数(random_param,套接字)吗?什么告诉函数在传递random_param时要引用?
有人告诉我阅读了我已经做过的文档,但这并没有使事情更清晰。
提前致谢。
Not necessarily. The JavaScript standard library (and various others) have lots of non-asynchronous callbacks. Think of the callbacks on the array functions
forEach
,map
,sort
...They come from the code calling the callback. In your case, code in the socket.io library you're using calls the callback with two arguments, which your callback receives in the parameters
err
anddata
.这是一个愚蠢的示例:一个函数调用带有随机数的回调: