비동기, Promise , async , await

Taro·2023년 9월 22일
0

JavaScript

목록 보기
1/1

비동기 (asynchronous)

동기(Sync) 의 반댓말로, 웹페이지를 새로고침없이 데이터를 불러오는 방식이다.

  • 필요한 부분만 업데이트 하기 때문에 속도와 성능 향상 가능

  • 요청과 응답이 동시에 일어나지 않아도 되기 때문에 동시에 다른작업을 할 수 있다

Promise

JacaScript 비동기 처리에 사용되는 객체이다.

  • Promise 를 사용함으로써 콜백지옥에서 벗어나기 쉬워졋다

기본구조

  test(1)then((result) => {
     console.log(1, result);
  });
  • 함수( 실행에필요한옵션(인자).then(처리할콜백)

Promise 의 3가지 상태

Pending(대기)

new Promise(function(resolve, reject){
});
  • new Promise() 메소드 호출시 콜백함수 선언 가능 , 인자는 resloe, reject이다.

Fulfilled(이행)

function getData() {
  new Promise(function(resolve, reject){
     var data = 100;
     resolve(data);
 });
}

/* <resolve() 의 결과 값 data 를 resolveData 로 받는다> */

  getData().then(function(resolvedData) {
    console.log(resolvedData); // 100
});

  • 위의 Pending(대기) 상태에서 resolve 를 실행하면 이행(Fulfilled) 상태가 된다

  • then() 을 이용하여 처리 결과 값을 받을 수 있다

Rejected(실패)

function getData() {
  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
});
  • 실패 상태가 되면 실패한 이유(실패 처리의 결과 값) 을 catch() 로 받을 수 있다

여러개의 프로미스 연결 (Promise Chaining)


new Promise(function(resolve, reject){
  setTimeout(function() {
    resolve(1);
  }, 2000);
})
  .then(function(result) {
    console.log(result); // 1
    return result + 10;
})
  .then(function(result) {
    console.log(result); // 11
    return result + 20;
})
  .then(function(result) {
    console.log(result); // 31
});
  • 프로미스 객체 하나 생성 후 setTimeOut()를 이용하여 2초 후 resolve( ) 를 호출하는 예제

  • resolve() 가 호출되면 대기->이행 으로 넘어가며 첫 번째 .then() 의 로직으로 넘어간다 then(1) -> then(11) -> then(31) 으로 넘어가며 최종 결과 값 31

프로미스의 예외처리 방법

  1. then( )을 이용
  getData().then(
    handleSuccess,
    handleError
 );
  1. catch( ) 를 이용
  getData().then().catch();
  • 더 많은 예외 처리 상황을 위하여 가급적 catch( )를 사용하자!
  1. 예시
// catch()로 오류를 감지하는 코드
  function getData() {
    return new Promise(function(resolve, reject) {
      resolve('hi');
    });
}

  getData().then(function(result) {
    console.log(result); // hi
    throw new Error("Error in then()");
    }).catch(function(err) {
      console.log('then error : ', err); // then error :  Error: Error in then()
});

async/await 란?

Promise의 가독성이 안좋다는 단점을 보완해주며 디버깅이 쉬워진 비동기 처리방법

Promise 예시

  const makeRequest = () =>
      getJSON()
      .then(data => {
          console.log(data);
          return "done";
      })

  makeRequest();

async/await 예시

  const makeRequest = async () => {
      console.log(await getJSON());
      return "done";
  }

  makeRequest();
  • 한눈에 봐도 Promise 보다 가독성이 좋다는것을 알수 있다!

async 사용해보기

async 함수

async function asyncFunction() {
  return 'Hello, world!';
}
 
  • 'async' 키워드를 함수 앞에 붙여서 비동기함수로 만든다 (Function 생략가능)
  • 비동기 함수는 항상 Promise를 반환

await 키워드

async function asyncFunction() {
  const result = await someAsyncOperation();  // 기다림
  console.log(result);
}
  • await 키워드는 async 함수 안에서만 사용가능
  • await 키워드 위에 Promies가 오면 해당 Promise가 완료될 때 까지 기다린 후에 결과 반환
  • 비동기 작업이 완료될 때까지 함수의 실행을 일시중지 시킴
  async function fetchUser() {
    try {
      const response = await fetch('https://api.example.com/user');
      const user = await response.json();
      return user;
    } catch (error) {
      console.error('Error fetching user:', error);
      throw new Error('Failed to fetch user.');
    }
}

  fetchUser()
    .then((user) => {
      console.log('Fetched user:', user);
    })
    .catch((error) => {
      console.error('Fetch user failed:', error.message);
    });
  • fetchUser() 함수 호출 후 then 메서드 사용하여 작업완료시 결과 반환
  • then 을 사용하여 연쇄적으로 비동기 작업 처리 가능

예시 2

  async function fetchData() {
    console.log('Fetching data...');  // 1. 로그 출력

    // 비동기 작업: 2초 후에 'Data fetched!'를 반환
    return new Promise((resolve) => {
      setTimeout(() => {
        resolve('Data fetched!');  // 2. 비동기 작업 완료
      }, 2000);
    });
  }

  async function processData() {
    console.log('Processing data...');  // 4. 로그 출력

    const data = await fetchData();  // 5. await: 비동기 작업 완료까지 기다림
    console.log('Received data:', data);  // 6. 로그 출력
  }

  console.log('Start');  // 0. 로그 출력

  processData();  // 3. processData 호출

  console.log('End');  // 7. 로그 출력

실행순서

  • "Start" 출력
  • processData() 호출하면서 "Processing data..." 출력
  • processData() 안에서 fetchData() 호출
  • fetchData()에서 "Fetching data..." 출력 후, 2초 대기
  • 2초 후, "Data fetched!" 반환하면서 fetchData() 완료
  • processData()에서 받은 데이터를 출력하면서 "Received data: Data * fetched!" 출력
  • "End" 출력
profile
기록하며 공부하는곳

0개의 댓글