Managing Asynchronous Operations with Promise and Async/Await in JavaScript

2 min read .

In JavaScript, managing asynchronous operations can be done using Promise and async/await. These features provide a cleaner and more understandable way to write asynchronous code. How to implement Promise and async/await for managing asynchronous operations in JavaScript.

1. Creating State with a Simple Object

To start, we can use a simple object to store state. Here, we’ll store a text in the state object:

let state = {
    text: 'text here'
};

2. Creating Asynchronous Functions with Promise

Next, we’ll create two functions, callFirstName and callLastName, that return Promise. These functions simulate data fetching that takes some time.

function callFirstName() {
    return new Promise((resolve) => {
        setTimeout(() => {
            resolve('John');
        }, 1000);
    });
}

function callLastName() {
    return new Promise((resolve) => {
        setTimeout(() => {
            resolve('Doe');
        }, 3000);
    });
}
  • callFirstName: Returns a Promise that resolves to the first name John after 1 second.
  • callLastName: Returns a Promise that resolves to the last name Doe after 3 seconds.

3. Combining First and Last Names with Async/Await

To combine the results from the two asynchronous functions, we can use async/await. The fullName function will await the results of callFirstName and callLastName, and then combine both names.

async function fullName() {
    const first = await callFirstName();
    const last = await callLastName();

    state.text = first + ' ' + last;
    console.log(state.text); // Output: John Doe
}
  • await: Waits for the results of callFirstName and callLastName before continuing to the next lines of code.
  • state.text: Updates the state with the full name (John Doe).

4. Handling Asynchronous Operations with Error Management

You can also create Promise that handles execution time and returns messages based on certain conditions. Here is an example of handling success and error conditions in a Promise:

function cobaPromise() {
    return new Promise((resolve, reject) => {
        const time = 1000;
        if (time < 2000) {
            setTimeout(() => {
                resolve('done');
            }, time);
        } else {
            reject('too long');
        }
    });
}
  • resolve: Returns the message “done” if the time condition is met (less than 2000 ms).
  • reject: Returns the message “too long” if the time condition is not met.

5. Handling Promise with Async/Await and Error Management

Using async/await, we can handle Promise more easily, including error handling with try/catch.

async function coba() {
    try {
        state.text = await cobaPromise();
        console.log(state.text); // Output: done
    } catch (err) {
        state.text = err;
        console.log(state.text); // Output: too long
    }
}
  • try: Attempts to run cobaPromise() and updates the state if successful.
  • catch: Catches the error if the Promise fails and updates the state with the error message.

Conclusion

Using Promise and async/await in JavaScript allows you to manage asynchronous operations in a cleaner and more understandable way. This approach enables you to manage the flow of program execution more predictively, handle errors well, and ensure that your application remains responsive and manageable. Whether in simple cases like name concatenation or in more complex scenarios, Promise and async/await are valuable tools in JavaScript development.

See Also

chevron-up