Async Javascript

비동기식 알아보기!

Node.js v15.1.0 Documentation

공식문서로 fs.readFile 알아보기!


☝️ callback

// script.js
function runCallback() {
  resetTitle();
  playVideo();

  delay(1000, () => {
    pauseVideo();
    displayTitle();

    delay(500, () => {
      highlightTitle();

      delay(2000, resetTitle);
    });
  });
}
// 나머지 생략

// callback.js
const delay = (wait, callback) => {
  setTimeout(callback, wait);
}

✌️ promise constructor

// script.js
function runPromise() {
  resetTitle();
  playVideo();

  sleep(1000).then((param) => {
    console.log(param);
    pauseVideo();
    displayTitle();
    return 'world';
  })
    .then((param) => {
      console.log(param);
      sleep(500);
    })
    // .then(sleep.bind(null, 500))
    .then(highlightTitle)
    .then(sleep.bind(null, 2000))
    .then(resetTitle)
}

// 나머지 생략

// promiseConstructor.js
const sleep = (wait) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve('hello')
    }, wait);
  });
}

promise는 비동기 연산이 종료된 이후의 결과값이나 실패 이유를 처리하기 위한 처리기를 연결할 수 있도록 하는 역할을 해요. 프로미스를 사용하면 비동기 메서드에서 마치 동기 메서드처럼 값을 반환할 수 있죠!

다만 최종 결과를 반환하지는 않고, 프로미스를 반환해서 미래의 어떤 시점에 결과를 제공해요.

promise의 세 가지 상태