TIL

이건선·2023년 6월 7일

알아볼것

목록 보기
9/13

Promise와 async/await

Promise:
Promise는 JavaScript에서 비동기 작업의 최종 완료 또는 실패와 그 결과 값을 나타내는 객체입니다. 즉, 앞서 수행한 작업이 완료되지 않아도 다음 작업을 계속 진행할 수 있게 하는 비동기 처리에 활용됩니다. 이는 JavaScript의 경우 싱글 스레드 기반 언어로, 특히 서버 환경인 Node.js에서 I/O 처리 등의 작업을 효율적으로 관리하게 합니다.

Promise는 pending(대기), fulfilled(이행), rejected(거부) 세 가지 상태를 가집니다. 처음 생성될 때는 pending 상태이며, 작업이 성공적으로 완료되면 fulfilled, 작업이 실패하거나 오류가 발생하면 rejected 상태가 됩니다.

Promise는 then, catch, finally 메소드를 통해 연속적인 작업을 처리할 수 있습니다.

const promise = new Promise((resolve, reject) => {
  // some asynchronous operation
});

promise
  .then(value => {
    // on fulfillment (completion)
  })
  .catch(reason => {
    // on rejection (error)
  })
  .finally(() => {
    // executed regardless of whether the promise was fulfilled or rejected
  });

Async/Await:
Async/Await는 ES2017(ECMAScript 2017)에서 도입된 비동기 처리 패턴으로, 기본적으로 Promise를 더 쉽고 명확하게 다룰 수 있게 해줍니다.

  • async: 함수 앞에 async 키워드를 사용하면 해당 함수는 항상 Promise를 반환합니다. 일반 값이 반환되면 JavaScript는 그 값을 Promise로 감싸 자동으로 반환합니다.
  • await: await 키워드는 async 함수 내에서만 사용할 수 있으며 Promise의 완료를 기다리고 그 결과를 반환합니다.

Async/Await는 Promise를 더 깔끔하게 처리할 수 있으며, 콜백 함수와 Promise의 중첩을 줄여 코드의 가독성을 높여줍니다.

async function asyncFunc() {
  try {
    const result = await someAsyncOperation();
    // result now holds the resolved value of the promise
    console.log(result);
  } catch (error) {
    // If the promise was rejected, the error will be caught here
    console.log(error);
  }
}

asyncFunc();

클로저(Closure)

클로저는 함수와 함수가 선언될 때의 렉시컬 환경(Lexical Environment)의 조합입니다.

JavaScript와 같은 프로그래밍 언어에서, 클로저는 함수 내에서 선언된 내부 함수가 외부 함수의 변수에 접근할 수 있도록 하는 기능을 말합니다. 즉, 함수가 정의될 때의 환경을 '기억'하는 함수를 의미합니다. 이로 인해 함수가 상위 스코프의 변수를 참조하고, 그 변수가 생존할 수 있도록 합니다.

function outerFunction(outerVariable) {
  return function innerFunction(innerVariable) {
    console.log('outerVariable:', outerVariable);
    console.log('innerVariable:', innerVariable);
  }
}

const newFunction = outerFunction('outside');
newFunction('inside');  // logs "outerVariable: outside" and "innerVariable: inside"

위 코드에서 outerFunctioninnerFunction을 반환하며, innerFunction은 외부 함수의 변수 outerVariable에 접근합니다. 이렇게 innerFunction은 자신이 선언된 렉시컬 환경을 '기억'하고 있으므로 클로저라고 할 수 있습니다.

클로저는 데이터 은닉, 객체 데이터 속성, 커링, 함수 팩토리, 메모이제이션 등 다양한 패턴과 기법에 사용됩니다.

profile
멋지게 기록하자

0개의 댓글