Home >Web Front-end >JS Tutorial >What is a callback function in js
A callback function is a function that is executed after another function has completed execution, allowing asynchronous functions to notify other functions without blocking the main thread. It is passed as a parameter to the async function and is called when the async function completes execution. Callback functions provide advantages in asynchronous programming, improved code readability, and modularity, but they also bring the disadvantages of callback hell and lazy binding.
What is a callback function
In JavaScript, a callback function is a function that is executed after another function has completed function to run. It allows asynchronous functions (functions that run without blocking the main thread) to notify other functions when they are completed.
How to use the callback function
The callback function is passed as a parameter to the asynchronous function. When the async function completes execution, it calls the callback function, passing the results of any calculations.
Example: Using XMLHttpRequest
<code class="javascript">const xhr = new XMLHttpRequest(); xhr.open('GET', 'https://example.com/api/data'); xhr.onload = function() { // 当请求完成时执行的回调函数 if (xhr.status === 200) { console.log(xhr.responseText); } else { console.error('请求失败:', xhr.status); } }; xhr.send();</code>
In this example, the onload
event listener is a callback function that executes when the request is completed . If the request is successful, it logs the response text.
Advantages
Disadvantages
The above is the detailed content of What is a callback function in js. For more information, please follow other related articles on the PHP Chinese website!