자바스크립트 비동기, 동기

citron03·2022년 1월 19일
0

html, css, js

목록 보기
13/43

자바스크립트는 비동기로 작동한다.
하지만 웹 페이지의 로딩을 기다리거나, 입력을 기다리거나, 다운로드가 완료된 후에 실행되야 하는 코드가 있을 수 있다.
따라서 이때는 동기적으로 작동이 될 수 있도록 한다.

// 비동기
const printHi = () => {
  setTimeout(() => {
    console.log("안녕!")
  }, Math.random() * 100);
}
const printWhat = () =>{
  setTimeout(() => {
    console.log("우리 뭐할까?");
  }, Math.random() * 100);
}
const printBye = () => {
  setTimeout(() => {
    console.log("잘가!")
  }, Math.random() * 100);
}

printHi();
printWhat();
printBye();
// 실행되는 순서가 매번 랜덤이다.

Callback 함수로 동기화

// 콜백 함수를 사용해 동기화 한다.
const printHi = (name, callback) =>{
  setTimeout(() => {
    console.log(name + "님, 안녕하세요!");
    callback();
  }, Math.random() * 100);
}

printHi("김이박", () => {
  printHi("최최최", () => {
    printHi("끝", () => {})
  })
});
// setTime의 대기 시간에 관계없이 앞 순서 함수의 실행이 우선된다.

Promise 사용

const printHi = (name) =>{
  // reject는 에러의 경우 실행되게 한다.
  // resolve는 성공한 결과값을 내보낸다.
  return new Promise((resolve, reject) =>{
    setTimeout(() => {
      if(name === "err")
        reject("에러!")
      else{
        console.log(name + "님, 안녕하세요!");
        resolve(name, "성공!");
      }
    }, Math.random() * 100);
  });
}

printHi("처음")
  .then((user1) => {
    console.log(printHi("err")
      .catch(() => console.log("실패!"))); 
    // 에러 발생, "실패!"가 출력된다.
    // 출력된 Promise의 상태는 rejected, 결과에 "에러!"가 저장된다.
    return printHi(user1 + " 다음")
  })
  .then((user2) => {
    console.log(printHi("^^")); 
    // Promise의 상태는 fullfilled, 결과에 "^^"가 저장된다.
  return printHi(user2 + " 마지막");
  })

/* 
출력값은 다음과 같다.
처음님, 안녕하세요!
Promise {}
실패!
처음 다음님, 안녕하세요!
Promise {}
처음 다음 마지막님, 안녕하세요!
^^님, 안녕하세요! <- 이 부분은 동기화 되지 않았기에 나타나는 위치가 매번 다르다.
마지막 출력보다 앞설 수도, 뒤쳐질 수도 있다.
*/

Promise.all을 이용해 여러 함수의 동기화를 한 번에 진행할 수도 있다.

async, await을 이용한 동기화

const printA = () => {
  return new Promise((resolve) =>{
      setTimeout(() => {
        resolve("AAA");
    }, 100);
  });
}

const printB = () => {
  return new Promise((resolve) =>{
      setTimeout(() => {
        resolve(" B B");
    }, 500);
  });
}

const printAB = async () => {
  let a = await printA().then((data) => (data.toLowerCase()));
  let b = await printB().then((data) => (data.toLowerCase()));
  
  return a + b;
}

printAB().then(data => console.log(data)); // Promise 객체로 리턴되기에 then을 사용해 출력해야 한다.
// aaa  b b 가 출력된다.
profile
🙌🙌🙌🙌

0개의 댓글