Skip to content

Instantly share code, notes, and snippets.

@DaleSeo
Last active July 16, 2021 13:19
Show Gist options
  • Save DaleSeo/0c84a7361d55311b10558bd55e25f2e2 to your computer and use it in GitHub Desktop.
Save DaleSeo/0c84a7361d55311b10558bd55e25f2e2 to your computer and use it in GitHub Desktop.
JS Async Async/Await
async function fetchAuthorName(postId) {
const postResponse = await fetch(`https://jsonplaceholder.typicode.com/posts/${postId}`);
const post = await postResponse.json();
const userId = post.userId;
const userResponse = await fetch(`https://jsonplaceholder.typicode.com/users/${userId}`)
const user = await userResponse.json();
return user.name;
}
fetchAuthorName(1).then(name => console.log("name:", name));
function fetchAuthorName(postId) {
return fetch(`https://jsonplaceholder.typicode.com/posts/${postId}`)
.then(response => response.json())
.then(post => post.userId)
.then(userId => {
return fetch(`https://jsonplaceholder.typicode.com/users/${userId}`)
.then(response => response.json())
.then(user => user.name);
});
}
fetchAuthorName(1).then(name => console.log("name:", name));
async function fetchAuthorName(postId) {
const postResponse = await fetch(`https://jsonplaceholder.typicode.com/posts/${postId}`);
const post = await postResponse.json();
const userId = post.userId;
try {
const userResponse = await fetch(`https://jsonplaceholder.typicode.com/users/${userId}`)
const user = await userResponse.json();
return user.name;
} catch (err) {
console.log('Faile to fetch user:', err);
return "Unknown";
}
}
fetchAuthorName(1).then(name => console.log("name:", name));
async function printAuthorName(postId) {
const name = await fetchAuthorName(postId);
console.log("name:", name);
}
printAuthorName(1);
@hyunW3
Copy link

hyunW3 commented Jul 16, 2021

안녕하세요! 여기에 작성해도 되는지 모르겠지만, 자바스크립트를 공부하면서 DaleSeo님의 블로그글 비동기 처리 3부 읽던도중 궁금증이 생겨서 여쭙습니다
fetchAuthorName_async_await.js 코드 세번째줄인 const post = await postResponse.json(); 에서 await를 하는 이유가 궁금합니다.
만약 비동기처리가 필요해서 시간이 걸린다고해도 blocking구문으로 처리해도 큰 차이가 없을 것같아서 await구문이 필요한 이유가 있나요? 있다면 어떤 이유인지 공부합니다.
ps. 공부하는데 좋은 글 작성해주셔서 감사합니다:)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment