簡體   English   中英

了解 javascript function 調用

[英]understanding javascript function call

仍在學習 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);

這是一個簡化的代碼示例。 它刪除了異步的東西,因為它不需要理解。

 // 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接收您的callbackXYZopts並返回您可以調用的 function ,傳入params

當您調用返回的 function 並將其傳遞給params時,返回的 function 將調用您的原始回調,並將來自optionsparams的數據傳遞給它。

不!

  • dowork是 function ,它返回另一個 function
  • 將另一個 function 分配給const main
  • 然后調用這個main(返回promise的函數)

您也可以在不聲明任何內容的情況下運行此代碼:

...
await dowork(callbackXYZ, options)(params);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM