DEV Community

Cover image for HarmonyOS Development: Asynchronous Concurrent Operation
程序员一鸣
程序员一鸣

Posted on

HarmonyOS Development: Asynchronous Concurrent Operation

Foreword

this article is based on Api12 

the so-called asynchronous, to put it bluntly, means that we can continue to execute the next operation without waiting for the execution result of the previous one. Compared with synchronization, asynchronous operation can process multiple tasks at the same time without affecting the execution of other tasks due to the time-consuming of one task, thus improving the concurrent processing capability of the program. In actual development, especially when the application starts initialization, asynchronous initialization is often the first choice in development in order not to block the program. In Hongmeng, how do we carry out asynchronous concurrent operation? Use the system-provided Promise and async/await can be easily done. 

Simple Case 

use the setTimeout function simulates an asynchronous operation.

 

private getMessage(): Promise<string> { return new Promise((resolve: Function) => { setTimeout(() => { resolve("===") }, 1000) }) } 
Enter fullscreen mode Exit fullscreen mode

Write execution logic

 

console.log("===") this.getMessage().then((result) => { console.log(result) }) console.log("===") 
Enter fullscreen mode Exit fullscreen mode

since the getMessage method is an asynchronous operation, the printing situation is as follows. From the above simulation code, it confirms the beginning that asynchronous does not back block the execution of the following program. 

Image description

This article briefly from the following three directions: 

1 What is Promise

2. Asynchronous callback receiving success and failure

3. Use in conjunction with async/await

4. Relevant summary

one, what is Promise 

first of all,Promise It is an object used to handle asynchronous operations, and provides a state mechanism to manage the different stages of asynchronous operations. Using Promise has two characteristics. The first characteristic, it can be combined async/await the second feature of converting asynchronous operations to a style similar to synchronous operations is that normal asynchronous operations use callback functions to handle the results of success or failure. 

The Promise provides three states. When the Promise object is created, it is in the pending (in progress) state, and after the asynchronous operation is completed, it is converted to the fulfilled (completed) or rejected (rejected) state. The specific simple case is as follows:

 

promise.then((result) => { }).catch((error: BusinessError) => { }); 
Enter fullscreen mode Exit fullscreen mode

second, asynchronous callback reception success and failure 

asynchronous callbacks, mainly using the then method to receive the results, the callback failure result of the catch method is the same as the above case. It should be noted that the then method can receive one parameter or two parameters, one parameter, indicating that when the Promise object state changes to fulled, the then method will automatically call this callback function. When there are two parameters, one function handles the fulled state and the other functions handles the rejected state.

 

promise.then((result) => { }).catch((error: BusinessError) => { }); 
Enter fullscreen mode Exit fullscreen mode

You can go to the official api to check, most of the methods, more or less provide this way of operation, such as network requests, such as database operations, etc., can be said to be common. 

Image description

III. Use in conjunction with async/await

async/await is a Promise syntax sugar used to handle asynchronous operations. As mentioned above, combined use can convert asynchronous operations into a style similar to synchronous operations. For example, in the case in the foreword, we use async/await to make a simple transformation:

 

 private async printLog() { console.log("===") let message = await this.getMessage() console.log(message) console.log("===") } 
Enter fullscreen mode Exit fullscreen mode

the above code is changed after async/await form, print the log as follows: 

Image description

it can be clearly found that the final printing is executed after waiting for the end of the previous one, which realizes the synchronous operation. 

The async function is a function that returns a Promise object and is used to represent an asynchronous operation. Inside, you can use the await keyword to wait for the resolution of a Promise object and then return the result of its resolution. If an exception is thrown, it will eventually be passed to the onRejected() method of the Promise object. 

IV. Relevant Summary 

in when used in conjunction with async/await, one thing to note, the await keyword must be combined with async. These two are used together and are indispensable. When the synchronization style is used, how can we get errors? After all, there is no catch method. In fact, we can create try/catch ourselves to catch exceptions.

 private async printLog() { try { console.log("===") let message = await this.getMessage() console.log(message) console.log("===") } catch (e) { console.error("===:" + e); } } 
Enter fullscreen mode Exit fullscreen mode

Top comments (0)