I'm trying to understand how parameters are already assigned when passed into callback functions. For example, in the mysql npm package Connection.js the .connect method passes a callback with an err paramaeter. I'm trying to understand the step by step details of how the .connect callback function err param is initialized and assigned.
mysql.connect(function(err) {
if (err) {
console.error('error connecting: ' + err.stack);
}
console.log('connected as id ' + connection.threadId);
});
My understanding of the connect call is this.
First, mysql.connect is invoked, which is a reference to
Connection.prototype.connect = function connect(options, callback)
in \node_modules\mysql\lib\Connection.js
Then, the code inside the connect function executes and ends with the line
this._protocol.handshake(options, bindToCurrentDomain(callback));
Control is then passed back to the anonymous callback function(err), which can now reference the err object since it has now been assigned.
Is this correct?
If not, any insight into this would be appreciated. In particular, I'm trying to understand
1) What is happening step by step during the execution of the call to .connect and how it exectues then hands control back to the anonymous callback.
2) How the anonymous callback has access to the assigned err param.
3) Is the answer to #2 essentialy the pattern (in essence of what occurs, not exact implementation details) for how callbacks with params "auto assigned"? (e.g. req and res params in express.Router().route(function(req,res)...)
Thanks