I apologize for the inconvenience, but I encountered an issue while attempting to access the URL https://api.example.com/news. This problem might be related to the URL itself or the network connection. Please ensure that the URL is valid and try accessing it again. If the issue persists, it could be a temporary network problem.
If you have any other questions or need further assistance with the topic at hand, feel free to ask, and I'll be happy to help!
Asynchronous Programming in HarmonyOS Next: Core Concepts and Practical Techniques
I. Core Concepts of Asynchronous Programming
HarmonyOS Next implements efficient asynchronous programming based on the single-threaded model of ArkTS. It leverages Promises and async/await to address the traditional callback hell problem, thereby enhancing code maintainability. The core advantages include:
- Non-blocking Execution: The main thread continues to respond to UI operations while asynchronous tasks are suspended.
- Simplified Concurrency Logic: Chainable calls replace deeply nested callbacks.
- Unified Error Handling: Exceptions are centrally managed using catch or try/catch.
II. Core Usage of Promises
1. States and Basic Syntax
Promises have three states:
- Pending: The asynchronous operation is in progress.
- Fulfilled: The task is successfully completed.
- Rejected: The task has failed.
Example: Creating a Promise Object
const fetchData = new Promise<string>((resolve, reject) => {
setTimeout(() => {
const success = Math.random() > 0.5;
success ? resolve('Data loaded successfully') : reject('Request timed out');
}, 1000);
});
fetchData
.then(result => console.log(result))
.catch(error => console.error(error));
2. Chaining and Error Handling
Use .then()
to chain multiple asynchronous tasks and avoid callback nesting.
// Simulate user login process
login(userId: string)
.then(token => getUserInfo(token))
.then(info => saveLocalStorage(info))
.catch(error => showToast('Process failed: ' + error));
III. Advanced Development with async/await
1. Basic Syntax and Execution Flow
- async Function Declaration: Declares an asynchronous function that implicitly returns a Promise.
- await Suspension: Waits for the Promise to complete before proceeding with subsequent code.
Example: Encapsulating Network Requests
async function loadUserData() {
try {
const token = await fetchToken();
const data = await fetchUserInfo(token);
return processData(data);
} catch (error) {
console.error('Loading failed:', error);
throw error;
}
}
2. Optimizing Concurrent Execution
Use Promise.all
to improve the efficiency of multiple independent tasks.
// Load images and configuration concurrently
async function initApp() {
const [images, config] = await Promise.all([
fetchImageList(),
loadAppConfig()
]);
// Merge results and render
}
IV. Practical Asynchronous Data Loading
1. Network Request Scenarios
Encapsulate an HTTP request module for unified interception.
async function safeFetch(url: string) {
const response = await fetch(url);
if (!response.ok) throw new Error(`HTTP ${response.status}`);
return response.json();
}
// Usage example
async function loadNews() {
const news = await safeFetch('https://api.example.com/news');
updateUI(news);
}
2. File Read/Write Scenarios
Implement asynchronous file operations using @ohos.fileio
.
async function writeLog(message: string) {
const filePath = 'logs/app.log';
try {
await fileio.writeText(filePath, message + '\n', { append: true });
} catch (e) {
console.error('Log writing failed:', e);
}
}
Top comments (0)