Asynchronous programming in JavaScript is a way to execute non-blocking code, allowing other parts of the program to continue running while waiting for a long-running operation to complete. Here's an example of asynchronous programming in JavaScript using callbacks:
function getData(callback) { // Simulate a long-running operation with setTimeout setTimeout(function() { const data = [1, 2, 3, 4, 5]; callback(data); }, 1000); } function displayData(data) { console.log(data); } // Call getData with displayData as a callback function getData(displayData); console.log("This code is executed before the data is retrieved.");
getData
function simulates a long-running operation using setTimeout
, and takes a callback function as an argument. Once the operation is complete, getData
calls the callback function with the resulting data.displayData
function is defined as a separate function to handle the data once it is retrieved. This function is passed as a callback to getData
.getData
is called with displayData
as the callback function, and the program continues running while the data is retrieved. The last console.log
statement is executed before the data is retrieved, demonstrating the non-blocking nature of asynchronous programming in JavaScript.
No comments:
Post a Comment