JavaScript Fetch Code
使用Async/Await
js
const request = fetch(...);
const fetchDataAsync = async () => {
try {
let response = await request;
let body = await response.text();
console.log(body);
} catch (error) {
console.error("Error fetching data:", error);
}
};
fetchDataAsync();
js
const request = fetch(...);
(async () => {
let response = await request;
let body = await response.text();
console.log(body);
})();
使用Promises
js
const request = fetch(...);
const fetchDataWithPromises = () => {
return request
.then((response) => response.text())
.then((body) => {
return body;
})
.catch((error) => {
return error;
});
};
fetchDataWithPromises().then((resp) => {
console.log(resp);
});
js
const request = fetch(...);
request.then((response) => {
response.text().then((body) => {
console.log(body);
})
})
These refactored versions provide two alternatives for handling the asynchronous nature of the fetch
API. The first one uses async/await
, making the code more readable and concise, while the second one utilizes Promises for a more traditional approach. Both versions include error handling to handle potential issues during the data fetching process. Choose the one that best fits your coding style or project requirements.