Created
September 18, 2018 08:33
-
-
Save edqwerty1/b114d66525b0d76d7ef3e929c33901a5 to your computer and use it in GitHub Desktop.
JS fetch async examples with error handling and comparison to promise.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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