-
21.[React, JS] JS 비동기처리와 Promise, async, awaitJava Script & Type Script 2023. 1. 7. 12:04728x90
Axios: promise를 기반으로 http를 이용해서 서버와 통신하기 위해 사용하는 패키지
AXIOS에서 get메서드를 이용하려면 인자로 url과 config를 받아야 함.
Async, await를 이용해 비동기처리
비동기처리? Promise? Async? Await?
이 네가지를 알아보겠음!
동기
Synchronous : 동시에 발생하는- 순차적/직렬적으로 태스크를 수행한다.
- 요청을 보냈다면, 응답을 받아야 다음 동작이 이루어진다.
- 순차적으로 실행되므로, 어떤 작업이 수행중이라면 뒤의 작업은 대기한다.
- 블로킹(작업 중단)이 발생한다.
비동기
Asynchronous : 동시에 발생하지 않는- 병렬적으로 태스크를 수행한다.
- 현재 작업의 종료여부와 무관하게 다음 작업을 실행한다.
- 그러므로 동기 방식과는 달리 완료 순서가 보장되지 않는다.
- 블로킹이 발생하지 않는다.
동기 방식은
손님이 주문을 하고 >> 커피가 나올 때 까지 기다려서 >> 커피를 받아야 한다.
비동기 방식은
우선 주문을 받고 >> 손님은 커피가 나오는 순서를 신경쓰지 않고 >> 진동벨이 울리면 커피를 받는다.
동기와 비동기처리
동기 Synchronous : 요청 후 응답을 받아야 다음 동작 실행
비동기 Asynchronous : 요청 보낸 후 응답과 관계없이 다음 동작 실행
JS는 단일 스레드 프로그래밍 언어로, 단일 호출 스택이 있어 한번에 하나의 일을 처리하는 동기 방식이다.
비동기의 필요성: 하나의 호출스택만 있기 때문에 하나의 함수를 처리하는데 오랜 시간이 걸린다면 다음 실행할 함수에 지장을 줄 수 있다는 문제. 단일 호출스택을 가진 JS에서 비동기를 구현하는 방법 중 하나가 promise이다.
new Promise()로 프로미스를 생성하고 종료될 때까지 3가지 상태를 갖는다.
1. Pending(대기) : 비동기 처리 로직이 아직 완료되지 않은 상태
2. fulfilled(이행) : 비동기 처리가 완료되어 프로미스가 결과 값을 반환해준 상태
3. Rejected(실패) : 비동기 처리가 실패하거나 오류가 발생한 상태
- Pending 대기
new Promise()메서드를 호출하면 대기상태가 된다
이 메서드를 호출할 땐 콜백함수를 선언할 수 있고, 그 인자는 resolve, reject.
new Promise(function(resolve, reject) { // ... });
- Fulfilled (이행)
콜백함수 인자 resolve를 아래와같이 실행하면 fufilled 이행 상태가 된다.
new Promise(function(resolve, reject) { resolve(); });
이행상태가 되면 아래와 같이 then()을 이용하여 처리결과 값을 받을 수 있다.
function getData() { return new Promise(function(resolve, reject) { var data = 100; resolve(data); }); } // resolve()의 결과 값 data를 resolvedData로 받음 getData().then(function(resolvedData) { console.log(resolvedData); // 100 });
- Rejected (실패)
New Promise() 로 프로미스 객체를 생성할 때 콜백함수로 reject를 아래와 같이 호출하면 실패 rejected상태가 된다.
new Promise(function(resolve, reject) { reject(); });
그리고 실패상태가 되면 catch()문을 이용해 실패한 이유(실패처리의 결과 값)을 받을 수 있다.
function getData() { return new Promise(function(resolve, reject) { reject(new Error("Request is failed")); }); } // reject()의 결과 값 Error를 err에 받음 getData().then().catch(function(err) { console.log(err); // Error: Request is failed });
프로미스 처리 흐름 - 출처: MDN
Promise함수를 이용해 비동기처리하기
function getData() { return new Promise(function(resolve, reject) { $.get('url', function(response) { if (response) { resolve(response); } reject(new Error("Request is failed")); }); }); } // 위 $.get() 호출 결과에 따라 'response' 또는 'Error' 출력 getData().then(function(data) { console.log(data); // response 값 출력 }).catch(function(err) { console.error(err); // Error 출력 });
서버에서 제대로 응답을 받아오면 resolve()메서드를 호출, 응답이없으면 reject()메서드를 호출한다.
호출된 메서드에 따라 then()이나 catch()로 분기하여 응답결과 또는 오류를 출력할 수도 있다.
async, await
async/await는 Promise를 더욱 쉽게 사용할 수 있게 돕는 ES7문법이다.
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));
해당 함수 내부에서 Promise 앞부분에 await 키워드를 사용한다. await 키워드는 async 키워드가 붙어있는 함수 내부에서만 사용할 수 있으며 비동기 함수가 리턴하는 Promise로 부터 결과값을 추출해준다.
await 키워드를 사용하면 일반 비동기 처리처럼 바로 실행이 다음 라인으로 넘어가는 것이 아니라 결과값을 얻을 수 있을 때까지 기다려준다. 따라서 일반적인 동기 코드 처리와 동일한 흐름으로 (함수 호출 후 결과값을 변수에 할당하는 식으로) 코드를 작성할 수 있으며, 따라서 코드를 읽기도 한결 수월해진다.
이렇게 하면 Promise가 끝날 때까지 기다리고, 결과 값을 특정 변수에 담을 수 있다
동기/비동기 구분없이 try, catch구문으로 일관되게 예외 처리를 할 수 있다는 부분도 async/await를 사용할 때의 큰 이점 중 하나이다.
728x90'Java Script & Type Script' 카테고리의 다른 글