Hello, I am V brother, very curious, in ArkTS to achieve asynchronous programming is how, today's content to talk about this issue, summarized some learning notes, to share with you, in ArkTS to achieve asynchronous programming can be mainly through the following ways:
1. Utilizationasync
cap (a poem)await
Keywords.
async
A function is a special kind of function that writes asynchronous code in the same way as synchronous code. In theasync
Inside a function, you can use theawait
expression to wait for an asynchronous operation to return a Promise object. This approach allows asynchronous code to be written and read closer to the style of synchronous code, improving readability and maintainability of the code.
// Define aasyncfunction (math.)
async function myAsyncFunction() {
// utilizationawaitWaiting for an asynchronous operation to complete
const result = await someAsyncOperation();
(result);
}
What is the difference between the async function and the await keyword?
async
cap (a poem)await
are two keywords used for asynchronous programming in JavaScript that work together to simplify writing and understanding asynchronous code, but they each have different uses and meanings:
async keyword
-
async
is a keyword for declaring asynchronous functions. - Any use of
async
Declared functions all automatically return aPromise
Object. - If the function ends up executing normally, the
Promise
will be resolved and the return value of the function will be returned. - If an error is thrown in the function, the
Promise
will be rejected (reject). -
async
Functions can contain one or more internalawait
Expressions.
await keyword
-
await
is a function that is used to wait for aPromise
The keyword for the object resolve. -
await
can only be found inasync
function is used internally. - When executing the
await
expression, the JavaScript engine will suspend theasync
function is executed until the waitingPromise
be resolved. - in the event that
Promise
Resolved.await
The expression returnsPromise
The value of the - in the event that
Promise
Rejected.await
expression throws a reason for the rejection, which can be done via thetry...catch
Statement Capture. -
await
This is usually followed by an asynchronous operation, such as one that returns aPromise
of the function call.
The difference between them
-
async
is used to declare functions, whileawait
is used to wait for asynchronous operations inside a function. -
async
itself doesn't suspend code execution, it just lets the function return aPromise
whereasawait
is used to pause code execution until thePromise
be resolved. -
async
May not be associated withawait
together, the function still returns aPromise
but will not be suspended. -
await
Must be used inasync
function internally, otherwise a syntax error will be thrown.
typical example
// async function declaration
async function fetchData() {
// Waiting for an asynchronous operation to complete
const data = await fetchSomeData(); // Here the await
return data;
}
// To be used on its own async
async function justAsync() {
('This is an async function, but without await.');
}
// utilization await
async function useAwait() {
('Before await.');
await justAsync(); // wait for justAsync fulfillment
('After await.');
}
So, V reminds me.async
cap (a poem)await
are two complementary concepts in asynchronous programming.async
is used to declare asynchronous functions, whileawait
Used inside an asynchronous function to wait for the completion of an asynchronous operation, beginners need to be careful not to get confused.
2. Using Promise objects
Above we have mentioned the Promise object, Promise is an object that handles asynchronous operations, it provides a state mechanism to manage the different phases of an asynchronous operation, representing the finalization (or failure) of an asynchronous operation and its resultant value, and provides methods to register callback functions to handle the result of the success or failure of the asynchronous operation.Promise has three states: PENDING, FULFILLED, and REJECTED.
// Create a newPromise
const myPromise = new Promise((resolve, reject) => {
// asynchronous operation
if (/* asynchronous operation成功 */) {
resolve("Success");
} else {
reject("Error");
}
});
// utilizationthencap (a poem)catchdeal withPromiseresults
((value) => {
(value); // "Success"
}).catch((error) => {
(error); // "Error"
});
3. Exception handling
In an asynchronous function, if an error occurs, you can pass thetry...catch
statement to catch the exception.
async function myAsyncFunction() {
try {
const result = await someAsyncOperation();
(result);
} catch (error) {
(error);
}
}
4. Concurrent execution of asynchronous tasks
It is possible to useto concurrently execute multiple asynchronous tasks and wait for them all to complete.
async function concurrentTasks() {
const [result1, result2] = await ([
asyncOperation1(),
asyncOperation2()
]);
(result1, result2);
}
5. Use of the Actor model
The Actor model used by the ArkTS language is a concurrent programming model in which each Actor is an independent unit of computation with its own state and behavior, and communicates and collaborates with other Actors through message passing.
1. Overview of the Actor model
In the Actor model, each Actor can receive asynchronous messages and respond according to the message content and the current state. message passing between Actors is asynchronous, and the Actor that sends a message does not need to wait for the response of the Actor that receives the message, thus realizing concurrent execution. Since each Actor is independent and there is no shared state between them, there is no need for locking mechanisms and synchronization operations, avoiding some common concurrent programming problems such as deadlocks and race conditions.
2. Data transmission objects
The data objects supported for transfer by the ArkTS language can be categorized into four types: ordinary objects, transferable objects, shareable objects, and Native bound objects. The transfer of ordinary objects is serialized through a structured cloning algorithm that supports a variety of types, including base types, Date, String, RegExp, Array, Map, Set and so on.
3. Realization examples
The following is an example of a producer-consumer problem implemented using the Actor model of ArkTS:
Actor model implementation of Producer and Consumer:
import taskpool from '@';
// Cross-thread concurrent tasks
@Concurrent
async function produce(): Promise<number>{
// Add production-related logic
("test producing...");
return ();
}
class Consumer {
public consume(value: number) {
// Add consumption-related logic
("test consuming value: " + value);
}
}
@Entry
@Component
struct Index {
@State message: string = 'Hello I am VG';
build() {
Row() {
Column() {
Text()
.fontSize(50)
.fontWeight()
Button() {
Text("start")
}.onClick(() => {
let produceTask: = new (produce);
let consumer: Consumer = new Consumer();
for (let index: number = 0; index < 10; index++) {
// Execute production asynchronous concurrent tasks
(produceTask).then((res: number) => {
(res);
}).catch((e: Error) => {
();
})
}
})
.width('20%')
.height('20%')
}
.width('100%')
}
.height('100%')
}
}
In this example, theproduce
function is an asynchronous function that simulates the production process of a producer and returns a random number as the product.Consumer
class containsconsume
method for consuming the product. In the UI, when the user clicks on the "start" button, 10 production tasks will be started, and each time the production task is completed, it will call theConsumer
(used form a nominal expression)consume
method to consume the product.
This example shows how to implement concurrent execution in ArkTS using the Actor model, where producers and consumers communicate with each other through asynchronous message passing without waiting for the other's response, thus enabling efficient concurrent processing.
ultimate
ArkTS provides powerful asynchronous programming capabilities , allowing developers to effectively handle asynchronous tasks , improve program performance and responsiveness . For brothers who have TypeScript experience is not a feeling of finding true love. Concerned about Wei brother love programming, Hongmeng open heaven and earth, you and I are all the same people.