still learning to javascript. How does this below code work?
when main(params)
is called does it mean it under-the-hood calls dowork(callbackXYZ, options, params)
?
const { dowork } = require('some_lib');
async function callbackXYZ(src, tgt, params) => {
// ...logic
}
const main = dowork(callbackXYZ, options);
await main(params);
Here's a simplified code example. It removes the async stuff, since it's not needed to understand.
// The callback you provide to `dowork`
// The internals of `dowork` will give invoke it with the given args
function callbackXYZ(src, tgt, params) {
console.log("src is:", src);
console.log("tgt is:", tgt);
console.log("params is:", params);
}
// The options you provide to `dowork`
var options = {src: "foo", tgt: "bar"};
// Invoking `dowork` receives your callback and options, and returns
// a new function that has access to both of these arguments.
const main = dowork(callbackXYZ, options);
// The params you provide to the returned function
const params = {my: "params"};
// Invoking the returned function
main(params);
// Here's the `dowork`. It receives your callback and options, and it
// returns a new function that expects you to pass it params.
// So that returned function has reference to the callback, options
// and params.
// The body of the returned function, simply invokes your callback and
// passes it data from the options and params you provided
function dowork(callback, opts) {
return function(params) {
callback(opts.src, opts.tgt, params);
}
}
So dowork
receives your callbackXYZ
and the opts
and returns a function that you can invoke, passing in the params
.
When you invoke that returned function, and pass it the params
, that returned function invokes your original callback, and passes it data both from the options
and the params
.