How to use Async/Await in Promise.
Tags: webdev, javascript, beginners
Published: 2024-05-23 20:59:13

Hello, everyone. In this article, I would explain promise async/await in javascript. It is recommended to read the following article and understand the concept of asynchronous and synchronous processing before reading this article. This is because these concepts is connected with Promise. Moreover, please read the following article for information on how to use Promise chaining, a different implementation of Promise.
[➡async/sync in Javascript　](https://dev.to/makoto0825/asyncsync-in-javascript-438e)
[➡How to use Promise chaining in Javascript.](https://dev.to/makoto0825/how-to-use-promise-chaining-in-javascript-391c)

## What is promise?
Promise is an object that represents the completion or failure of synchronous processing. By using this object, you can wait for asynchronous processing to complete and then execute the next process sequentially.

In the following case, it is not possible to output in the order of ABC. Instead, it outputs in the order of ACB. This is because the asynchronous function setTimeout delays the execution by 4000ms, causing console.log("C") to be executed before console.log("B").

```javascript
  <script>
    //=== function declaration ==========
    const func = () => {
      console.log("B");
    };

    //  === program start ==========
    console.log("A");
    setTimeout(func, 4000); //async function
    console.log("C");
  </script>
```

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ncl6eiz2edklz2ep3vn3.png)


However, if you use Promise Async/Await, you can output in the order of ABC.

```javascript
  <script>
    //===promise declaration ==========
    const pro = new Promise((resolve) => {
      setTimeout(() => {
        func(); //processing 2
        resolve();
      }, 4000);
    });

    //=== function declaration ==========
    const func = () => {
      console.log("B");
    };
    async function process() {
      message = await pro;
      console.log("C"); // Subsequent processing 3
    }

    // === program start ==========
    console.log("A"); //processing 1
    process();
  </script>
```


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/adbw05su240mk3m64x64.png)



## How to use promise.
 This is basic format for a promise.

```javascript
    const num = 10;
    const pro = new Promise((resolve, reject) => {
      if (num > 0) {
        resolve("success!!!!!");
      } else {
        reject("failure");
      }
    });
    console.log(pro); //output success

```
**returned object**
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vjie9l45dtgtukiqz6w2.png)


Promise can take the functions resolve and reject as arguments. And return promise object.

- resolve: Function called when the operation succeeds
- reject: Function called when the process fails.

In this case, num is greater than 0 so it returns Promise object in successful state thanks to resolve.

## Async/Await
When the Promise object is in a successful state due to resolve, subsequent processing can be executed using Async/Await.

```javascript
  <script>
    const num = 10;

    const pro = new Promise((resolve, reject) => {
      if (num > 0) {
        console.log("process1");
        resolve("success!!!!!");
      } else {
        console.log("process failure");
        reject("failure");
      }
    });

    async function process() {
      const message = await pro; // wait until the promise is resolved or rejected
      console.log(message); // Subsequent processing1

      console.log("process2"); // Subsequent processing2

      console.log("process3"); // Subsequent processing3
    }
    process();
  </script>
```

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/empxnlujcmw1m33eovh4.png)

Await executes asynchronous processes, waits for them to complete, and then proceeds with subsequent tasks. These sequences of actions can be defined within an async function.

<u>The following is the convention to use  Async/Await.</u>
- When using a Promise object (assuming an asynchronous operation), you prefix the object with 'await'.

- When using await, the function where it's used must be marked with async.

- After executing a process with await, you can perform subsequent tasks.Note:This must be implemented within an async function.

## Try/Catch and reject
When the Promise object is in a Failure state due to reject, error can be handled using by try and catch.

```javascript
  <script>
    const num = -5;

    const pro = new Promise((resolve, reject) => {
      if (num > 0) {
        console.log("process1");
        resolve("success!!!!!");
      } else {
        console.log("failure1");
        reject("failure2");
      }
    });

    async function process() {
      try {
        const message = await pro; // wait until the promise is resolved or rejected
        console.log(message); // Subsequent processing1
        console.log("process2"); // Subsequent processing2
        console.log("process3"); // Subsequent processing3
      } catch (error) {
        console.log(error);
        console.log("failure3");
      }
    }
    process();
  </script>
```

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wedkiid3431kmjtfs6ki.png)


In this case, num is lesser than 0 so it returns Promise object in failure state thanks to reject.Hence, the processings inside of catch are executed. This is assuming error handling. The processings inside of try are not executed.Moreover, you can use the argument passed to the reject function by specifying an argument in the catch block.

<u>The following is the convention to use Try/Catch.</u>

- Subsequent processing after process success is enclosed in try

- Subsequent processing after process failure is enclosed in catch.

## Asynchronous Function and Promise Async/Await

If you use promise Async/Await, Asynchronous processing can be executed synchronously.

```javascript
  <script>
    //===promise declaration ==========
    const pro = new Promise((resolve) => {
      setTimeout(() => {
        func(); //processing 2
        resolve();
      }, 4000);
    });

    //=== function declaration ==========
    const func = () => {
      console.log("B");
    };
    async function process() {
      message = await pro;
      console.log("C"); // Subsequent processing 3
    }

    // === program start ==========
    console.log("A"); //processing 1
    process();
  </script>
```

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/muh3gvtizqhex0l5tbvf.png)