JavaScript 동기 / 비동기

Heidi·2022년 4월 22일
0

Javascript

목록 보기
6/6
post-thumbnail

01 일반 함수

<script>

function testFunc1(){
  console.log('testFunc1()');

  let startTime = new Date().getTime()
  while( new Date().getTime() - startTime < 1000 ); 
  // 1초가 지난 후 true 처리

  testFunc2();  
}

function testFunc2(){
  console.log('testFunc2()');
}

testFunc1();


</script>

'testFunc1()'가 먼저 출력되고 1초 후
'testFunc2()'가 이후 출력된다.


02 Promise(1)

<script>

//new promise 호출과 비동기 처리 시작
const promise = new Promise((resolve, reject) => {
// resolve, reject도 인자임과 동시에 함수를 호출할 수 있는 포인터이다.
//인자의 이름은 변경 가능하나 관습적으로 쓴다.

  resolve()         
  reject()

});

//promise의 내장함수
//then -> resolve
//catch -> reject
promise.then(()=>{
  console.log('1. promise() then() called')
  }).catch(()=>{
    console.log('2.promise() catch() called')
  }
);

</script>

'testFunc1()'가 먼저 출력되고 1초 후

'testFunc2()'
1. promise() then() called 가 출력된다.


promise는 excutor를 만들어서 넣어줘야 한다.
그냥 함수식도 되지만 관습적으로 화살표 함수를 사용한다.

위 코드를 실행했을 때 catch의 내용이 찍히지 않는 것을 확인할 수 있다.
promise는 resolve와 reject 둘 중 하나만 실행시킨다.
(reject를 먼저 호출하면 resolve가 안찍힌다)


참고 : 컴파일과 런타임 메모리 할당

new 객체는 런타임에 할당이 된다.
함수가 컴파일 시 메모리가 할당되고 new 객체가 컴파일 이후 런타임 때 메모리가 할당되므로 이후에 출력되는 것을 확인할 수 있다.


03 Promise(2)

<script>

function asyncCheckAdult(age) {
  return new Promise( (resolve, reject) => {
    if( age >= 20) resolve(age);
    else reject(age);
  })
}

const promiseCheckAdult = asyncCheckAdult(10);

promiseCheckAdult.then((age) => {
  console.log(`${age} is adult!!`);
}).catch((age) => {
  console.log(`${age} is not adult!!`);
});

//=============================================

function asyncCheckAdult(age) {
  return new Promise( (resolve, reject) => {
    if( age >= 20) resolve(age);
    else reject(age);
  })
}

const promiseCheckAdult1 = asyncCheckAdult(21);

promiseCheckAdult1.then((age) => {
  console.log(`${age} is adult!!`);
}).catch((age) => {
  console.log(`${age} is not adult!!`);
});

</script>

출력 순서는 다음과 같다
21 is adult!!
10 is not adult!!

신기한 점은, checkPoint 1과 2의 숫자를 바꿔도 출력순서가 같다는 점이다.
promiseCheckAdult과 promiseCheckAdult1의 위치나 순서 상관없이 resolve값이 무조건 reject보다 먼저 실행된다는 것을 확인할 수 있다.


04 Promise의 최신형 async await

참고 : async await의 목적

비동기 함수를 동기 함수처럼 간단히 표현

참고 : async await 사용시 주의사항

사용이 편해진만큼 내부구조를 이해하는데 어려울 수 있다.
때문에 promise를 충분히 이해한 후 async await를 사용하는 것이 좋다

<script>

function asyncCheckAdult(age) {
  if(age >= 20) { return age }      //성공했을때
  else throw new Error(age)         //실패했을때
}

</script>

new promise와 resolve, reject가 필요없어진다.
대신 reject 구현을 위해 throw를 사용한다.

profile
햇님쓰 개발일기장

0개의 댓글

관련 채용 정보