理解 javascript 函数调用

问题描述 投票:0回答:2

仍在学习 javascript。下面的代码是如何工作的? 当

main(params)
被调用时是否意味着它在幕后调用
dowork(callbackXYZ, options, params)

const { dowork } = require('some_lib');

async function callbackXYZ(src, tgt, params) => {
    // ...logic
}
const main = dowork(callbackXYZ, options);
await main(params);
javascript callback
2个回答
0
投票

这是一个简化的代码示例。它删除了异步内容,因为不需要理解它。

// 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);
  }
}

因此

dowork
接收您的
callbackXYZ
opts
并返回一个您可以调用的函数,传入
params

当您调用该返回函数并向其传递

params
时,该返回函数将调用您的原始回调,并向其传递来自
options
params
的数据。


-1
投票

不!

  • dowork
    是返回另一个函数的函数
  • 另一个功能被分配给
    const main
  • 然后调用这个 main (返回 Promise 的函数)

您也可以在不声明任何内容的情况下运行此代码:

...
await dowork(callbackXYZ, options)(params);
© www.soinside.com 2019 - 2024. All rights reserved.