DEV Community

Makoto Tsuga
Makoto Tsuga

Posted on

How to use Async/Await in Promise.

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 
➡How to use Promise chaining in Javascript.

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").

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

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

Image description

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

  <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>
Enter fullscreen mode Exit fullscreen mode

Image description

How to use promise.

This is basic format for a promise.

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

Enter fullscreen mode Exit fullscreen mode

returned object
Image description

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.

  <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>
Enter fullscreen mode Exit fullscreen mode

Image description

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.

The following is the convention to use Async/Await.

  • 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.

  <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>
Enter fullscreen mode Exit fullscreen mode

Image description

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.

The following is the convention to use Try/Catch.

  • 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.

  <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>
Enter fullscreen mode Exit fullscreen mode

Image description

Top comments (0)