[英]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:所以:
getData
is called, passing in a function that will log the argument it gets. getData
被调用,传入一个函数来记录它得到的参数。
getData
calls setTimeout
to schedule a callback in about 100ms, passing in another function for the timer to call. getData
调用setTimeout
以在大约 100 毫秒内安排回调,并传入另一个函数供计时器调用。
getData
returns. getData
返回。
About 100ms later, the browser's timer subsystem triggers a call to the callback passed to setTimeout
.大约 100 毫秒后,浏览器的计时器子系统触发对传递给
setTimeout
的回调的调用。
That callback creates an object and calls cb
, passing the object to it.该回调创建一个对象并调用
cb
,将对象传递给它。
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.