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
Create a
Promiseobject with a resolve/reject function to handle asynchronous logic.Use
.then()and.catch()to register success and failure handlers.Alternatively, use
asyncfunctions andawaitfor more readable code.Use
try/catchblocks to handle exceptions withinasyncfunctions.
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);
})
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.
});
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%')
}
}
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();
Limitations or Considerations
- Async functions return Promise objects.
- Await pauses execution until the Promise is fulfilled or rejected.
- Use
try/catchto catch exceptions inside async functions. - Use global
unhandledRejectionlistener to handle uncaught Promise rejections.
Top comments (0)