ES6 스터디 정리 : async/await

Llux lux·2022년 4월 19일
0

ES6 스터디

목록 보기
9/21

await/async

Promise 를 대체하여 더욱 더 편하고 보기 좋게 사용하기 위한 방법
Promise 를 대체하여 사용된다.

함수 선언 시 async 로 선언하여 비동기 함수임을 선언한다.
내부에서 fetch, json 등 함수 응답 수신이 필요한 경우 await 를 앞에 작성하여 수신까지 비동기로 대기한다.

//promise 로 작성한 코드
const getMoviesPromise = () => { 
    fetch("https://yts.mx/api/v2/list_movies.json")
        .then(res => res.json())
        .then(json => console.log(json))
        .catch(e => console.log(e));
};

//async await 로 작성한 코드
const getMoviesAsync = async() => {
    const response = await fetch("https://yts.mx/api/v2/list_movies.json");
    const json = await response.json();
    console.log(json);
}

getMoviesAsync();

try ~ catch, finally

try, catch 문을 통해 간단하게 에러를 처리하고 완료 되었을때 처리를 할수 있다.

const getMoviesAsync = async() => {
    try{
        const response = await fetch("https://yts.mx/api2/v2/list_movies.json");
        const json = await response.json();
        console.log(json);
    }
    catch(e){
      //catch 문에서 에러를 수신하여 처리할 수 있다.
        console.log(e);
    }
    finally{
      //성공, 실패 등 모든 처리 완료가 끝나면 해당 구문이 실행된다.
        console.log('done');
    }
}

Parallel Async Await

동시에 async await 함수를 호출하는 방법
promise all 에 fetch 함수를 여러개 호출하고 리턴을 받는다.

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

        const [movieJon, upcomingJson] = await Promise.all([
            movieRes.json()
            ,upcomingRes.json()
        ]);

        console.log(movieJon);
        console.log(upcomingJson);
    }
    catch(e){
        console.log(e);
    }
    finally{
        console.log('done');
    }
}
profile
하하하

0개의 댓글