65 phút
JavaScript Bất đồng bộ và Gọi API
Callbacks
function fetchData(callback) {
setTimeout(() => {
callback("Data received!");
}, 2000);
}
fetchData(function(data) {
console.log(data); // "Data received!" after 2 seconds
});
Promises
function fetchData() {
return new Promise((resolve, reject) => {
setTimeout(() => {
const success = true;
if (success) {
resolve("Data fetched successfully!");
} else {
reject("Error fetching data");
}
}, 2000);
});
}
fetchData()
.then(data => console.log(data))
.catch(error => console.error(error));
Async/Await
async function getData() {
try {
const data = await fetchData();
console.log(data);
} catch (error) {
console.error(error);
}
}
getData();
Fetch API
// GET request
fetch('https://jsonplaceholder.typicode.com/posts')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
// POST request
fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
title: 'New Post',
body: 'This is a new post',
userId: 1
})
})
.then(response => response.json())
.then(data => console.log(data));
Xử lý lỗi
async function fetchWithErrorHandling() {
try {
const response = await fetch('https://jsonplaceholder.typicode.com/invalid-url');
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
return data;
} catch (error) {
console.error('Fetch failed:', error);
return null;
}
}