개인노트-인강

개인노트 nomad ES6의 정석 #9 Async / Await

roroism 2023. 2. 16. 20:31

# 9.0 Async Await

 

Async Await는 Promise의 업데이트라고 생각할 수 있습니다.

Async Await를 만든 이유는, 보기 좋은 코드를 만들기 위해서입니다.

기존의 then이나 catch 같은 것 들은 구식입니다. 왜냐하면 결국 많은 then을 사용해야 하기 때문입니다.

 

기본적으로 async/await는 많은 then이나 catch를 사용하지 않고, Promise 밖에서 값을 가져올 수 있는 방법입니다. 

## 사용법

await는 항상 async function 안에서만 사용할 수 있습니다.

then 대신에 await를 사용하면 됩니다.

// 기존 Promise
const getMoviesPromise = () => {
    fetch("https://yts.mx/api/v2/list_movies.json")
    .then((response) => {
        console.log(response);
        return response.json();
    })
    .then((potato) => console.log(potato))
    .catch((e) => console.log(`✔${e}`));
};
// --------------------------------
// async await
const getMoviesAsync = async () => {
    const response = await fetch("https://yts.mx/api/v2/list_movies.json");
    console.log(response);
    const json = await response.json();
    console.log(json);
};

getMoviesAsync();

await는 기본적으로 Promise가 끝나길 기다립니다. (성공만을 기다려주는 것이 아닙니다. resolve 되는 reject 되든 상관없이 단지 promise가 끝나길 기다립니다.)  

 

# 9.1 try catch finally

Async Await에서의 catch하는 방법.

## try catch

// 기존
const getMoviesAsync = async () => {
    const response = await fetch("https://yts.mx/api/v2/list_movies.json");
    console.log(response);
    const json = await response.json();
    console.log(json);
};

getMoviesAsync();

// try catch 추가
const getMoviesAsync = async () => {
    try {
        const response = await fetch("https://yts.mx/api/v2/list_movies.json");
        const json = await response.json();
        console.log(json);
    } catch(e) {
        console.log(`❌ ${e}`);
    }    
};

getMoviesAsync();

// finally 추가
const getMoviesAsync = async () => {
    try {
        const response = await fetch("https://yts.mx/api/v2/list_movies.json");
        const json = await response.json();
        console.log(json);
    } catch(e) {
        console.log(`❌ ${e}`);
    } finally {
        console.log("We are done!");
    }  
};

getMoviesAsync();

 

 

throw Error를 추가해본다면?

// throw Error를 추가해 본다면?
const getMoviesAsync = async () => {
    try {
        const response = await fetch("https://yts.mx/api/v2/list_movies.json");
        const json = await response.json();
        throw Error("Im hungry");
    } catch(e) {
        console.log(`❌ ${e}`);
    } finally {
        console.log("We are done!");
    }  
};

getMoviesAsync();
// 결과
// ❌ Error: Im hungry
// We are done!

throw로 던진 error message를 catch의 인수로 받습니다. 그리고

try catch는 try catch 블록안에만 있다면 await 밖에 있는 error까지 잡습니다.

## 6 Reasons Why JavaScript Async/Await Blows Promises Away

참고 사이트

https://hackernoon.com/6-reasons-why-javascripts-async-await-blows-promises-away-tutorial-c7ec10518dd9

 

# 9.2 Parallel Async Await

코드 예

const getMoviesAsync = async () => {
    try {
        const [moviesResponse, upcomingResponse] = await Promise.all([
          fetch("https://yts.mx/api/v2/list_movies.json"),
          fetch("https://yts.mx/api/v2/movie_suggestions.json?movie_id=100"),
        ]);

        const [movies, upcoming] = await Promise.all([
          moviesResponse.json(),
          upcomingResponse.json(),
        ]);

        console.log(movies, upcoming);
    } catch (e) {
        console.log(e);
    } finally {
        console.log("we are done");
    }
};

getMoviesAsync();