[JavaScript] 비동기, promise, promiseAll

김혜림·2023년 5월 17일
0

javascript

목록 보기
4/4

비동기 프로그래밍 언어에서 동기적인 기능을 구현해야 할 때 promise를 사용한다.

자바스크립트는 기본적으로 비동기 프로그래밍 언어입니다.

하지만 우리는 동기적인 프로그래밍이 필요한 경우가 있습니다.

예를들면, 로그인 할 때를 상상해봅시다.
아이디, 비밀번호를 입력한 후 서버에 로그인 요청을 보냅니다.
서버에서 로그인에 성공하면 로그인 토큰을 던져줄 겁니다.
그런데 서버의 응답은 조금의 시간이 걸릴 것이고,
자바스크립트는 비동기 언어이기 때문에 서버의 응답이 오기 전에 뒤의 코드를 실행할겁니다.

하지만 로그인을 성공했을 때 홈페이지 UI를 새로고침하는 코드는 서버로부터 로그인 토큰을 전달받은 이후에 동작해야 합니다.

이를 구현하기 위해서 자바스크립트에서는 Promise라는 표준 내장 객체를 지원합니다.

Promise

const getDataFromFilePromise = filePath => {
  return new Promise((resolve,reject)=>{
    fs.readFile(filePath,'utf-8',(err,data)=>{
      if(err){
        reject(err);
      } else{
        resolve(data);
      }
    })
  });
};

getDataFromFilePromise('README.md')
.then(data => console.log(data))
.catch(err => console.log(err));

위의 코드는 Promise 객체를 리턴하는 getDataFromFilePromise 메서드를 작성하고, 사용하는 예제입니다.

new Promise( (resolve,reject) => { 🅰️ } )

Promise 객체를 생성할 때는 전달인자로 콜백함수를 전달합니다.
Promise 객체가 new 키워드를 통해 새로 생성되었을 때,
제일 먼저 Promise 객체의 전달인자인 콜백함수 **(resolve,reject) => { 🅰️ }
가 실행됩니다.

콜백함수 내에서 내가 원하는 값이 도출되었으면 resolve(data)를 실행하고,
에러가 도출되었으면 reject(error) 를 실행합니다.

Promise( (resolve, reject) => { 🅰️ } ) 코드의 resolve, reject 콜백함수는 전달하는 방법이 따로 있습니다.

Promise객체.then( resolve메서드 작성 )
Promise객체.catch( reject메서드 작성 )

위와 같은 방식으로 resolve, reject 콜백함수를 전달하는 것입니다.
이렇게 주는 이유는 아마 Promise 내장 객체의 코드를 뜯어보면 알 수 있겠죠 😀 그래서 게시물의 아래쪽에 Promise 객체 코드를 첨부했습니다.

아무튼, 위의 코드에서는

getDataFromFilePromise('README.md')
.then(data => console.log(data))
.catch(err => console.log(err));

위와 같이 Promise 객체를 생성했으니까 resove 메서드는 data => console.log(data)텍스트 가 되겠구요, reject 메서드는 err => console.log(err)가 되겠습니다.

...

Promise 내장 객체 코드 뜯어보기.

declare type PromiseConstructorLike = new <T>(executor: (resolve: (value: T | PromiseLike<T>) => void, reject: (reason?: any) => void) => void) => PromiseLike<T>;

interface PromiseLike<T> {
    /**
     * Attaches callbacks for the resolution and/or rejection of the Promise.
     * @param onfulfilled The callback to execute when the Promise is resolved.
     * @param onrejected The callback to execute when the Promise is rejected.
     * @returns A Promise for the completion of which ever callback is executed.
     */
    then<TResult1 = T, TResult2 = never>(onfulfilled?: ((value: T) => TResult1 | PromiseLike<TResult1>) | undefined | null, onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | undefined | null): PromiseLike<TResult1 | TResult2>;
}

/**
 * Represents the completion of an asynchronous operation
 */
interface Promise<T> {
    /**
     * Attaches callbacks for the resolution and/or rejection of the Promise.
     * @param onfulfilled The callback to execute when the Promise is resolved.
     * @param onrejected The callback to execute when the Promise is rejected.
     * @returns A Promise for the completion of which ever callback is executed.
     */
    then<TResult1 = T, TResult2 = never>(onfulfilled?: ((value: T) => TResult1 | PromiseLike<TResult1>) | undefined | null, onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | undefined | null): Promise<TResult1 | TResult2>;

    /**
     * Attaches a callback for only the rejection of the Promise.
     * @param onrejected The callback to execute when the Promise is rejected.
     * @returns A Promise for the completion of the callback.
     */
    catch<TResult = never>(onrejected?: ((reason: any) => TResult | PromiseLike<TResult>) | undefined | null): Promise<T | TResult>;
}

이렇게 생겼으니까 분석해 보시면 되겠습니다.^^

profile
공부하는 혜림이😀

0개의 댓글