在JavaScript中,異步函數可以通過以下幾種方式提高代碼的可讀性:
async function fetchData() {
try {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
console.log(data);
} catch (error) {
console.error('Error fetching data:', error);
}
}
function fetchData() {
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error fetching data:', error));
}
async function processItems(items) {
for (const item of items) {
try {
const result = await fetch(`https://api.example.com/data/${item}`);
const data = await result.json();
console.log(data);
} catch (error) {
console.error(`Error fetching data for item ${item}:`, error);
}
}
}
async function fetchMultipleData() {
try {
const [data1, data2] = await Promise.all([
fetch('https://api.example.com/data/1').then(response => response.json()),
fetch('https://api.example.com/data/2').then(response => response.json()),
]);
console.log(data1, data2);
} catch (error) {
console.error('Error fetching multiple data:', error);
}
}
通過使用這些方法,你可以使JavaScript異步函數更易于閱讀和理解。