DEV Community

HarmonyOS
HarmonyOS

Posted on

Using Async-Await and Promises for Asynchronous Concurrency in ArkTS

Read the original article:Using Async-Await and Promises for Asynchronous Concurrency in ArkTS

Requirement Description

Promise and async/await are standard JavaScript asynchronous syntax that provides asynchronous concurrency capabilities. Asynchronous code is suspended and continues to execute later, ensuring that only one piece of code is executed at any given moment.

Background Knowledge

Asynchronous concurrency is a feature of programming languages that allows programs to continue executing other operations without waiting for certain operations to complete.

Promise and async/await are suited for the following scenarios:

  • Non-blocking I/O operations: network requests, file reading and writing, and timers
  • Lightweight tasks without CPU blocking
  • Clear logical dependencies in task order or parallel execution

Implementation Steps

  1. Create a Promise object with a resolve/reject function to handle asynchronous logic.

  2. Use .then() and .catch() to register success and failure handlers.

  3. Alternatively, use async functions and await for more readable code.

  4. Use try/catch blocks to handle exceptions within async functions.

Code Snippet / Configuration

Create and handle a Promise

const promise: Promise<number> = new Promise((resolve: Function, reject: Function) => {
  setTimeout(() => {
    const randomNumber: number = Math.random();
    if (randomNumber > 0.5) {
      resolve(randomNumber);
    } else {
      reject(new Error('Random number is too small'));
    }
  }, 1000);
})
Enter fullscreen mode Exit fullscreen mode

Handle Promise results

import { BusinessError } from '@kit.BasicServicesKit';

// Use the then method to define success and failure callbacks.
promise.then((result: number) => {
  console.info(`The number for success is ${result}`); // Executed on success.
}, (error: BusinessError) => {
  console.error(error.message); // Executed on failure.
});

// Use the then method to define a success callback and the catch method to define a failure callback.
promise.then((result: number) => {
  console.info(`Random number is ${result}`); // Executed on success.
}).catch((error: BusinessError) => {
  console.error(error.message); // Executed on failure.
});
Enter fullscreen mode Exit fullscreen mode

Handle unhandled Promise rejection globally

When a Promise object is rejected and not handled by the catch method, it triggers the unhandledRejection event. You can use the errorManager.on('unhandledrejection') interface to listen for this event.

Code Snippet / Configuration (Async/Await)

async function myAsyncFunction(): Promise<string> {
  const result: string = await new Promise((resolve: Function) => {
    setTimeout(() => {
      resolve('Hello, world!');
    }, 3000);
  });
  console.info(result); // Output: Hello, world!
  return result;
}

@Entry
@Component
struct Index {
  @State message: string = 'Hello World';
  build() {
    Row() {
      Column() {
        Text(this.message)
          .fontSize(50)
          .fontWeight(FontWeight.Bold)
          .onClick(async () => {
            let res = await myAsyncFunction();
            console.info('res is: ' + res);
          })
      }
      .width('100%')
    }
    .height('100%')
  }
}
Enter fullscreen mode Exit fullscreen mode

Using try/catch inside async function

async function myAsyncFunction(): Promise<void> {
  try {
    const result: string = await new Promise((resolve: Function) => {
      resolve('Hello, world!');
    });
  } catch (e) {
    console.error(`Get exception: ${e}`);
  }
}

myAsyncFunction();
Enter fullscreen mode Exit fullscreen mode

Limitations or Considerations

  • Async functions return Promise objects.
  • Await pauses execution until the Promise is fulfilled or rejected.
  • Use try/catch to catch exceptions inside async functions.
  • Use global unhandledRejection listener to handle uncaught Promise rejections.

Related Documents

Asynchronous Concurrency (Promise and Async/Await)-ArkTS Concurrency-ArkTS-Application Framework - HUAWEI Developers

Written by Ahmet Faruk Karakus

Top comments (0)