Skip to content

Instantly share code, notes, and snippets.

@edqwerty1
Created September 18, 2018 08:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save edqwerty1/b114d66525b0d76d7ef3e929c33901a5 to your computer and use it in GitHub Desktop.
Save edqwerty1/b114d66525b0d76d7ef3e929c33901a5 to your computer and use it in GitHub Desktop.
JS fetch async examples with error handling and comparison to promise.
// Old
function handleErrors(response) {
if (!response.ok) {
throw Error(response.statusText);
}
return response;
}
// GET
fetch(`/myAPI/GetMethod?param=${this.param}`, {
method: 'get',
credentials: 'same-origin',
headers: new Headers({
'Content-Type': 'application/json'
})
})
.then(handleErrors)
.then(response => response.json())
.then((response) => {
this.data = response;
})
.catch(error => {
alert(error);
});
// New
async function fetchAsync() {
try {
let response = await fetch(`/myAPI/GetMethod?param=${this.param}`, {
method: 'get',
credentials: 'same-origin',
headers: new Headers({
'Content-Type': 'application/json'
})
});
handleErrors(response);
let data = await response.json();
return data;
}
catch (error) {
alert(error);
}
}
// Post
fetch('/myAPI/PostMethod', {
method: 'post',
credentials: 'same-origin',
headers: new Headers({
'Content-Type': 'application/json'
}),
body: JSON.stringify(
this.search
),
})
.then(handleErrors)
.then(response => response.json())
.then((response) => {
this.data = response;
})
.catch(error => {
alert(error);
});
// New
async function fetchAsync() {
try {
let response = await fetch('/myAPI/PostMethod', {
method: 'post',
credentials: 'same-origin',
headers: new Headers({
'Content-Type': 'application/json'
}),
body: JSON.stringify(
this.search
)
});
handleErrors(response);
let data = await response.json();
return data;
}
catch (error) {
alert(error);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment