Read the original article:ArkTS Concurrency Guide 2025 Async Programming with Promises and Await (Part 1)
Learn how to write non-blocking code in ArkTS using Promises and async/await to keep your HarmonyOS Next apps smooth and responsive.
Introduction
Have you ever tapped a button on your smartwatch and waited awkwardly for the app to catch up? That slight lag often caused by blocking operations can lead to a poor user experience. On HarmonyOS Next, where devices are often constrained by size and resources, responsiveness is key.
Luckily, ArkTS provides asynchronous programming tools that help you execute tasks without freezing the UI. In this article, the first of a four-part guide, we’ll explore howPromisesandasync/awaitcan be used to manage asynchronous concurrency in ArkTS and improve application performance.Let’s dive in.
What Is Concurrency in ArkTS?
In ArkTS, concurrency refers to executing multiple tasks over time. This doesn’t always mean parallelism, especially on single-core devices. Instead, the system switches between tasks, like jumping between conversations, to make the best use of idle time.
ArkTS supports two main concurrency models:
- Asynchronous Concurrency (covered in this article): Ideal for I/O operations such as reading files or making network requests.
- Multithreaded Concurrency (coming up in Part 2): Best for CPU-heavy tasks that can be run in the background.
Writing Asynchronous Code with Promises
A Promise a JavaScript construct used to represent the eventual completion or failure of an asynchronous task. Think of it as a placeholder for a future value.
A Promise has three states:
- pending: initial state
- fulfilled: operation completed successfully
- rejected: operation failed Here’s a basic ArkTS example using a Promise to simulate an asynchronous task:
const promise: Promise<number> = new Promise((resolve, reject) => {
setTimeout(() => {
const randomNumber = Math.random();
if (randomNumber > 0.5) {
resolve(randomNumber);
} else {
reject(new Error('Random number is too small'));
}
}, 1000);
});
promise.then((result: number) => {
console.info(`Random number is ${result}`);
}).catch((error) => {
console.error(error.message);
});
🧠Tips
Always include .catch() to handle rejected Promises and avoid unhandled rejections that can crash your app.
Cleaner Code with Async/Await
While Promises are useful, chaining .then() and .catch() can become messy. That’s where async/await comes in.
Here’s a cleaner version of the previous example using async/await:
async function myAsyncFunction(): Promise<string> {
const result: string = await new Promise((resolve) => {
setTimeout(() => {
resolve('Hello, world!');
}, 3000);
});
console.info(result);
return result;
}
This asynchronous function waits for the Promise to resolve before continuing.You can also use try/catch to handle errors more gracefully:
async function myAsyncFunction(): Promise<void> {
try {
const result = await new Promise((resolve) => {
resolve('Hello, world!');
});
} catch (e) {
console.error(`Get exception: ${e}`);
}
}
Integrating with ArkTS UI
Let’s see how async functions can be used within a HarmonyOS Next component:
@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%')
}
}
When the user taps the text, the onClick event triggers an async function. The app stays responsive while the background task completes.
Conclusion
Asynchronous programming in ArkTS using Promises and async/await enables you to keep your UI responsive, your app efficient, and your users happy. It’s the foundation for building smooth experiences on resource-constrained devices like smartwatches and lightweight HarmonyOS terminals.
In the next part of this series, we’ll cover multithreaded concurrency using TaskPool and Worker, ideal for time-consuming or CPU-intensive tasks.
This article is Part 1 of a 4-part series on ArkTS Concurrency:
·🟢Part 1: Async Programming with Promises and Await
·🔴 Part 2: Multithreaded Programming with TaskPool and Worker
·🔴 Part 3: Inter-Thread Communication Patterns
·🔴 Part 4: Real-World Multithreaded Development Techniques
References
(https://forums.developer.huawei.com/forumPortal/en/topic/0201189234712057047?fid=0102647487706140266)
Written by Ahmet Faruk Karakus
Top comments (0)