简体   繁体   中英

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. Could some one let me know how this functions is executed into the javascript callback?

Here what is the function inside getData(cb) ? How it will be executed ? How the functions is passed as callback inside cb and return to the 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. In this case, it's asking for that callback to happen roughly 100ms later. getData returns before that happens.

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. So when the browser's timer calls the callback, the callback can call cb . The call to cb uses an object literal to create an object to pass to cb .

In the call to getData , the author is passing a function as cb that logs the data it receives.

So:

  1. getData is called, passing in a function that will log the argument it gets.

  2. getData calls setTimeout to schedule a callback in about 100ms, passing in another function for the timer to call.

  3. getData returns.

  4. About 100ms later, the browser's timer subsystem triggers a call to the callback passed to setTimeout .

  5. That callback creates an object and calls cb , passing the object to it.

  6. That callback (the one passed to getData ) logs the data object it receives.


¹ "closure" — see: SO , my anemic blog

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 秒,然后它将进入执行上下文并打印到控制台。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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