Reputation: 2109
I'm new in Javascript and I just start reading about callbacks. When I have to manage an entire process everything is clear to me, but I can't understand how they works when I have to make an http request for example. Reading about callbacks I've found this snippet:
function doHomework(subject, callback) {
alert(`Starting my ${subject} homework.`);
callback();
}
doHomework('math', function() {
alert('Finished my homework');
});
In this case it pretty clear to me that these are the main steps of the process:
I'll try to explain what in http request is not clear to me: I know that javascript is an event driven language so we can't rely on blocking functions since the execution of the code doesn't wait for completetion and so if we make a GET request for example we can't rely on the fact that on the next line of code the response is filled with the aspected data. To solve this problem a callback is used in order to be sure that data will be what we aspect. The problem is that I can't see where the callback is called. In jquery we can make something like this:
$.get(
"somepage.php",
{paramOne : 1, paramX : 'abc'},
function(data) {
alert('page content: ' + data);
}
);
I know that this jquery method may be outdated but I posted because it uses a callback function. Where is the callback invocation?
Upvotes: 0
Views: 111
Reputation: 138457
The engine (the browser) will start some background task doing the request, then when the request is done, it'll call the callback. The callback invocation is therefore somewhere deeply nested inside of the browsers sourcecode.¹
JavaScript is an interpreted language, which means that the interpreter can provide additional functionality that is not written in the language itself.
¹: For sure that only applies to native APIs, not to userland code like jQuery. jQuery will however call one of those native APIs internally, and will add a callback that calls you back.
// a simplified example:
function get(url, callback) {
fetch(url).then(function(res) { // the native API call adding a callback
callback(res); // which then calls back
});
}
Upvotes: 1