简体   繁体   English

这个函数中回调是如何执行的?

[英]How the callback is executed in this function?

 const getData = (cb) => { setTimeout( () => { cb({ data: ['there', 'is', 'stuff', 'here'] }) }, 100) } getData( data => { console.log(data); });

Here is the example of the javascript callback.这是 javascript 回调的示例。 Could some one let me know how this functions is executed into the javascript callback?有人可以让我知道这个函数是如何在 javascript 回调中执行的吗?

Here what is the function inside getData(cb) ?这里getData(cb)里面的函数是什么? How it will be executed ?它将如何执行? How the functions is passed as callback inside cb and return to the console.log函数如何在cb作为回调传递并返回到console.log

Regards.问候。

The function inside getData is a callback being passed to setTimeout , which is one way to schedule a call to a function to happen in the future. getData的函数是传递给setTimeout的回调,这是安排将来发生对函数的调用的一种方法。 In this case, it's asking for that callback to happen roughly 100ms later.在这种情况下,它要求回调在大约 100 毫秒后发生。 getData returns before that happens. getData在此之前返回。

The setTimeout callback is a closure ¹ over the context where it's created, which means it has access to cb even after getData has returned. setTimeout回调是创建它的上下文中的闭包¹,这意味着即使在getData返回之后它也可以访问cb So when the browser's timer calls the callback, the callback can call cb .所以当浏览器的定时器调用回调时,回调可以调用cb The call to cb uses an object literal to create an object to pass to cb .cb的调用使用对象字面量来创建要传递给cb的对象。

In the call to getData , the author is passing a function as cb that logs the data it receives.在对getData的调用中,作者将一个函数作为cb传递来记录它接收到的数据。

So:所以:

  1. getData is called, passing in a function that will log the argument it gets. getData被调用,传入一个函数来记录它得到的参数。

  2. getData calls setTimeout to schedule a callback in about 100ms, passing in another function for the timer to call. getData调用setTimeout以在大约 100 毫秒内安排回调,并传入另一个函数供计时器调用。

  3. getData returns. getData返回。

  4. About 100ms later, the browser's timer subsystem triggers a call to the callback passed to setTimeout .大约 100 毫秒后,浏览器的计时器子系统触发对传递给setTimeout的回调的调用。

  5. That callback creates an object and calls cb , passing the object to it.该回调创建一个对象并调用cb ,将对象传递给它。

  6. That callback (the one passed to getData ) logs the data object it receives.回调(传递给getData回调)记录它接收到的data对象。


¹ "closure" — see: SO , my anemic blog ¹“关闭”——见: SO我的贫血博客

In order to understand the code you can just simplify it by naming the anonymous functions.为了理解代码,您可以通过命名匿名函数来简化它。 One example could be:一个例子可能是:

function logData(data) {
    console.log(data);
}

const getData = (cb) => {  
    // `cb` is `logData` function when `getData` is called
    function timeoutCallback() {
        var data = { data: ['there', 'is', 'stuff', 'here'] };
        cb(data);
    }
    setTimeout(timeoutCallback, 100)
}

getData(logData);

Does that make sense?那有意义吗?

1- 创建第一个全局执行上下文 2- 将调用获取数据函数,然后它将在事件循环内等待 10 秒,然后它将进入执行上下文并打印到控制台。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM