본문 바로가기

STUDY/국비과정

[JAVA 웹 개발 공부] 국비지원 72일차 - async / await, 재귀호출, Cookie, 배열 인덱스 설정

async / await 

 

1. async와 await 사용 이유

콜백함수의 단점을 보완해주는 Promise, 그리고 또 Promise의 단점을 보완해주는 async/await.
async/await은 Promise와 다른 개념이 아니고 Promise를 사용하는 패턴이다.
async/await를 사용하는 가장 큰 이유는 Promise도 가독성이 썩 좋지 않다는 점이다. 코드가 깔끔하고 가독성이 좋아야 눈으로 로직 파악이 가능하고 디버깅이 쉬워지기 때문이다. 그리고 또 async/await로 코드의 양도 줄일 수 있다.
 

*Promise 문법

function p() {
	return new Promise((resolve, reject) => {
	    resolve('hello'); 
        // or reject(new Error('error');
	});
}

p().then((n) => console.log(n));


*async 문법

async function p2(){ // async을 지정해주면 Promise를 리턴하는 함수로 만들어준다.
  return 'hello2'; // 리턴값은 Promise{<resolved>: "hello2"} 자동 resolve해준다는걸 알 수있다.
  // reject는 throw 에러를 날리면 된다.
}

p2().then((n) => console.log(n));


한눈에 봐도 매우 직관적인 코드로 변했다고 느낄수 있다.
함수에 async만 붙이면 자동 Promise객체로 인식되고 return값은 resolve()값과 똑같다.

 

 

2. async와 await 사용법

function 키워드 앞에 async만 붙여주면 되고, 비동기로 처리되는 부분 앞에 await만 붙여주면 된다.
async가 붙은 함수는 프라미스를 반환하고, 프라미스가 아닌 것은 프라미스로 감싸 반환한다.
await 키워드를 만나면 프라미스가 처리(settled)될 때까지 기다린다.
그리고 프라미스가 처리가 완료되어 resolve(값) 되면 값만 따로 추출해서 리턴한다.

async/await가 Promise를 완벽히 대체하는 것이 아니다.
비동기는 Promise객체로 처리하고 async/await는 비동기를 동기식으로 처리하는 기법이다.
기존에는 Promise에 직접 .then()을 통해 동기처리를 했지만, await를 사용하면 바로 동기처리가 되기 떄문이다.

 

 

재귀호출

 

재귀 호출(recursive call)이란 함수 내부에서 함수가 자기 자신을 또다시 호출하는 행위를 의미한다.
이러한 재귀 호출은 자기가 자신을 계속해서 호출하므로, 끝없이 반복되게 된다.
따라서 함수 내에 재귀 호출을 중단하도록 조건이 변경될 명령문을 반드시 포함해야 한다.

<!DOCTYPE html>
<html>
<head>
    <meta charset='utf-8'>
    <title>Page Title</title>
</head>
<body>
    
</body>
<script>
    async function randomSucess() {
        if (Math.random() > 0.6) {
            return true;
        }
        throw new Error("실패하였음")
    }

    async function myLoop(count = 0, second = 1000) {
        try {
            let result = await randomSucess();
            console.log(result);
        } catch (e) {
            if (count >= 3) {
                console.log("너무 많은 시도로 중단합니다.");
                return;
            }
            console.log("다시 시도합니다.");
            setTimeout(() => {
                myLoop(count + 1, second * 2); // 재귀호출
            }, second);
        }
    }

    console.log("시작");
    myLoop();
    console.log("끝");
</script>
</html>

 

 

 

Cookie(쿠키)


자바스크립트는 document.cookie 속성을 이용하여 쿠키를 create, read, delete 할 수 있다.

 

1. create

document.cookie = "쿠키이름=쿠키값"


2. read

var x = document.cookie; // cookie1=value1; cookie2=value2;...


3. delete

// 1시간 뒤에 삭제
document.cookie = "max-age=3600";

// 바로 삭제
document.cookie = "max-age=0";

 

 

배열 인덱스값 설정

 

let numbers = [1, 2, 3, 4];
let [num1, num2, num3, num4] = numbers;

console.log(num1); // 1
console.log(num2); // 2
console.log(num3); // 3
console.log(num4); // 4

 

let numbers = [1, 2, 3, 4];
let [num1, , ...rest] = numbers;

console.log(num1); // 1
console.log(rest); // (2) [3, 4]

 

function sum(a, b, c, d) {
    console.log(a + b + c + d);
}

sum(...numbers); // 10