Phong cách đồng bộ của fetch trong JavaScript
Bạn cũng có thể làm việc với fetch
theo phong cách đồng bộ:
button.addEventListener('click', async function() {
let response = await fetch('/ajax.html');
let text = await response.text();
console.log(text);
});
Hãy viết lại đoạn mã sau theo phong cách đồng bộ:
button.addEventListener('click', function() {
let promise = fetch('/ajax.html')
.then(
response => {
if (response.ok) {
return response.text();
} else {
throw new Error('trạng thái phản hồi xấu');
}
},
).then(
text => {
console.log(text);
}
).catch(
error => {
console.log(error);
}
);
});