Advanced
Asynchronous JavaScript
JavaScript is single-threaded, meaning it executes one operation at a time. However, asynchronous programming allows JavaScript to handle time-consuming tasks (e.g., fetching data, reading files) without blocking the main execution thread.
Callbacks
A callback is a function passed as an argument to another function, which is then executed after the completion of an operation.
Example of a Callback Function
fetchData
simulates an asynchronous operation using setTimeout
.
processData
is executed after fetchData
completes.
Promises
A promise represents a future value and has three states:
Pending – Initial state, operation in progress.
Fulfilled – Operation completed successfully.
Rejected – Operation failed.
Creating a Promise
.then()
runs when the promise is resolved.
.catch()
runs when the promise is rejected.
.finally()
runs regardless of success or failure.
Conclusion
Asynchronous programming allows JavaScript to handle time-consuming operations efficiently. Callbacks, promises, and async/await help manage asynchronous workflows. The next section will explore DOM manipulation, which enables JavaScript to interact with web pages dynamically.
Join our Community Forum
Any other questions? Get in touch