Asynchronous JavaScript
In web development, asynchronous operations play a crucial role in ensuring smooth user experiences. With JavaScript, you can handle asynchronous tasks using promises and async/await.
Promises
Promises are objects used to handle the result (success or failure) of an asynchronous operation. They provide a cleaner and more structured way to work with asynchronous code. A promise can be in one of three states:
- Pending: The initial state, representing that the asynchronous operation is still ongoing.
- Fulfilled: The state when the asynchronous operation has completed successfully, and the promise has resolved with a value.
- Rejected: The state when the asynchronous operation has encountered an error, and the promise has been rejected with a reason.
Promises can be created using the Promise
constructor and the resolve
and reject
functions. For example:
1const myPromise = new Promise((resolve, reject) => {
2 // Simulating an asynchronous operation
3 setTimeout(() => {
4 const randomNumber = Math.random();
5 if (randomNumber < 0.5) {
6 resolve(randomNumber);
7 } else {
8 reject('Error: Random number is greater than or equal to 0.5');
9 }
10 }, 1000);
11});
12
13myPromise
14 .then((result) => {
15 console.log('Promise resolved:', result);
16 })
17 .catch((error) => {
18 console.error('Promise rejected:', error);
19 });
In this example, we create a myPromise
object that represents an asynchronous operation. The operation is simulated using a setTimeout
function. If a randomly generated number is less than 0.5, the promise is resolved and the result is passed to the then
method. Otherwise, the promise is rejected and the error is passed to the catch
method.
Async/Await
The async
and await
keywords provide a more concise and synchronous-looking way to work with promises. async
is used to define an asynchronous function, and await
is used to pause the execution of an asynchronous function and wait for the resolution of a promise.
Here's an example of using async
and await
to work with the myPromise
from the previous example:
1async function handleAsyncOperation() {
2 try {
3 const result = await myPromise;
4 console.log('Async operation resolved:', result);
5 } catch (error) {
6 console.error('Async operation rejected:', error);
7 }
8}
9
10handleAsyncOperation();
In this example, we define an async
function called handleAsyncOperation
that uses the await
keyword to pause the execution and wait for the resolution of the myPromise
. The result is then logged to the console. If the promise is rejected, the error is caught and logged.
Understanding how to work with asynchronous operations using promises and async/await is essential for developing asynchronous, non-blocking JavaScript code that improves performance and user experience.