Skip to content

Instantly share code, notes, and snippets.

@zimejin
Created March 20, 2020 08:19
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 zimejin/69026989d53df577a224639eaaa7adfb to your computer and use it in GitHub Desktop.
Save zimejin/69026989d53df577a224639eaaa7adfb to your computer and use it in GitHub Desktop.
fetch() with async and await - errors
var handleError = function (err) {
console.warn(err);
return new Response(JSON.stringify({
code: 400,
message: 'Stupid network Error'
}));
};
var getPost = async function () {
// Get the post data
var post = await (await fetch('https://jsonplaceholder.typicode.com/postses/5').catch(handleError)).json();
if (post.code && post.code === 400) return;
// Get the author
var author = await (await fetch('https://jnosplaceholder.typicode.com/users/' + post.userId).catch(handleError)).json();
if (author.code && author.code === 400) return;
console.log(post, author);
};
getPost();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment