티스토리 뷰

 

 

1. ES6 문법 2 - 비동기 함수

(1) 비동기 함수

-비동기 처리 : 특정 소스 코드의 연산이 완료될 때까지 기다리지 않고 다음 소스 코드를 실행하는 방식

-대표적으로 ajax 통신 및 setTimeout() 함수가 있음.

 (Java에서는 비동기처리를 위한 Listener가 있음)

-Event QUEUE : 작성한 코드를 분석? 실행?

(*자바는 하나의 실행이 종료될 때까지 기다림. JavaScript는 기다리지 않음.)

(*자바는 멀티스레드 / 자바스크립트는 싱글스레드)

(*스레드 : 실제 소스 코드를 실행하는 주체. 프로세스보다는 작은 것)

//비동기 처리 사용

console.log('---시작과 동시에 실행하는 부분----');//1
setTimeout(function () {
  console.log('---5초 후에 실행되는 부분---');//2
}, 5000);

console.log('---마지막에 실행되는 부분---');//3

/*
자바였다면
1번 출력 후 → 5초 후 2번 출력 → 3번 출력

자바스크립트는,
1번 출력 → 3번 출력 → 2번은 1번 출력 후 5초 후에 출력

---시작과 동시에 실행하는 부분----
---마지막에 실행되는 부분---
---5초 후에 실행되는 부분---
 */

 

(2) a-jax

-HTML 파일 생성 / 비동기만 확인할 거라 다른 건 필요없음.

(2-1) STS : New -  Spring Start Project

-controller

package com.example.demo.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class TestController {

		@RequestMapping("/")
		public String index() throws Exception{
			return "index";
		}
		@ResponseBody
		@RequestMapping("/ajax")
		public Object ajax() throws Exception{
			return "success";
		}
}

-src/main/resources  templates에 index.html 생성

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<!--jQeury-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

<script type="text/javascript">
$(document).ready(function(){
	$("#btn-test").on("click", function(){
		alert("test");
		
		$.ajax({
			url: "/ajax",
			type:"get",
			success: function(data){
				alert("ajax 통신성공");
				alert(data);
			},
			error: function(data){
				alert("ajax 실패");
			} 
		});
	});
});
function getData(){
	var tableData;
	$.get("http://lacalhost:9090/ajax", function(response){
		tableData = response;
	});
}
</script>
</head>
<body>
	<h1>async Test Page</h1>
	<button id="btn-test">클릭 시 ajax 통신</button>
</body>
</html>

-application.properties

server.port=9090

-결과 : 버튼 클릭시 알림창 뜨면 통신 성공

ajax가 작동하는 건 확인 ↓

ajax 통신 실행, 비동기 통신 진행.

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js">
</script>
<script type="text/javascript">
$(document).ready(function(){
	$("#btn-test").on("click", function(){
		alert("test");
		console.log(getData());  //undefined
//		alert(getData());
	});
});
function getData(){
	var tableData;
	$.get("http://localhost:9090/ajax", function(response){
		tableData = response;
	});
}
</script>
</head>
<body>
	<h1>async Test Page</h1>
	<button id="btn-test">클릭 시 ajax 통신</button>
</body>
</html>

-비동기 통신문제 해결 ↓ getDate2()

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js">
</script>
<script type="text/javascript">
$(document).ready(function(){

	$("#btn-test").on("click", function(){
		alert("test");
		console.log(getData());
//		alert(getData());
	});
    
   	$("#btn-test2").on("click", function(){
        getData2(function(tableData){
            console.log(tableData);
            alert(tableData);
        });
        alert("getData2 Play");
    });
});

function getData2(callbackFunc){
	$.get("http://localhost:9090/ajax", function(response){
		callbackFunc(response); //getData2(function(tableData)){...}
	});
}
/*
1. getData() 실행 시 변수 tableData를 생성하고, 기본값이 undefined로 초기화
2. ajax를 통한 비동기 통신 명령이 수행되고 콜백함수가 실행되기를 기다림
3. 현재 비어있는 tableData 변수를 return
4. 화면에 tableData의 데이터가 출력. 값은 undefined
5. ajax 통신으로 인한 콜백함수 실행, 서버에서 받아온 데이터를 tableData 변수에 대입
6. getData() 함수는 이미 리턴(return) 키워드를 실행하여 종료되었기 때문에
   tableData에 저장된 값은 사용할 수 없음. 메모리에서 삭제.
*/

function getData(){
	var tableData; //변수 선언 후 초기화하지 않으면 undefined
	//ajax 통신 실행, 비동기 통신 진행.
	$.get("http://localhost:9090/ajax", function(response){
		tableData = response;
	}); 
	/*eventQUEUE에 넣은 뒤, 응답을 기다리지 않고 리턴함.
	나중에 응답받아 tableData에 넣지만, tableData가 사용될 일이 없으니까 데이터 삭제.
	*/ 
	return tableData; // undefiend 출력되는 이유 ↑
}

</script>
</head>
<body>
	<h1>async Test Page</h1>
	<button id="btn-test">클릭 시 ajax 통신</button>
	<button id="btn-test2">비동기 통신 문제 해결 1</button>
</body>
</html>

 

(3) 비동기 함수 Promise

콜백이 또다른 콜백으로 이어지는 반복을 피하고자 만들어진 것?

-ES6에서 도입된 비동기 처리를 위한 명령어

-Promise 실행 시, 비동기 처리가 성공이면 resolve를 실행하고, 실패면 reject

 resolve - then ,  reject - catch 연결

 

(3-1) Promise의 상태

Pending Fulfilled Rejected
대기 성공 실패
비동기 처리 로직이 완료되지 않은 상태
new Promiss 명령어만 실행한 상태
작업만 걸어놓고 기다리는 상태
(차 시동 걸고 기다리고 있는 상태)
비동기 처리가 완료,
프로미스 결과값 반환 상태
비동기 처리 실패하여 오류 발생 상태

 

(3-2) Controller

package com.example.demo.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class TestController {

	@RequestMapping("/")
	public String index() throws Exception{
		return "index";
	}
	
	@ResponseBody
	@RequestMapping("/ajax")
	public Object ajax() throws Exception{
		return "success";
	}
	
    //추가
	@ResponseBody
	@RequestMapping("/ajax2")
	public Object ajax2(@RequestParam("data") String data) throws Exception{
		if(data.equals("ok")) {
			return "success";
		}else {
			return "error";
		}
	}
}

 

(3-3)index.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js">
</script>
<script type="text/javascript">
$(document).ready(function(){
	$("#btn-test3").on("click", function(){
		getData3()
		.then(function(tableData){ //resolve 실행 시, then 실행
			console.log(tableData);
		})
		.catch(function(err){ //reject 실행 시, catch 실행
			console.log(err);
		});
		alert("getData3 Play");
	});	
});

function getData3(callback){
	return new Promise(function(resolve, reject){ //성공시 resolve, 실패시 reject
		$.get("http://localhost:9090/ajax", function(response){
			if(response == "success"){
				resolve(response);//성공 시 데이터 실어서 보내라
			}
			else{
				reject(response);
			}
		});	
	});	
}

</script>
</head>
<body>
	<h1>async Test Page</h1>
	<button id="btn-test">클릭 시 ajax 통신</button>
	<button id="btn-test2">비동기 통신 문제 해결 1</button>
	<button id="btn-test3">프로미스(PROMISS)</button>
</body>
</html>

 

(3-3) 웹브라우저 검사(f12)

[소스]에서 표시(디버깅 표시)해서 값이 제대로 넘어가는지 확인할 수 있음.

 

ㅇㅇ

es6_0415.zip
0.01MB

댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/07   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31
글 보관함