在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异步函数更易于阅读和理解。