Synchronous fetch style in JavaScript
You can also work with fetch
in
synchronous style:
button.addEventListener('click', async function() {
let response = await fetch('/ajax.html');
let text = await response.text();
console.log(text);
});
Rewrite the following code in sync style:
button.addEventListener('click', function() {
let promise = fetch('/ajax.html')
.then(
response => {
if (response.ok) {
return response.text();
} else {
throw new Error('bad response status');
}
},
).then(
text => {
console.log(text);
}
).catch(
error => {
console.log(error);
}
);
});