본문 바로가기
자바스크립트와 캔버스

jQuery 프로미스 - await 처리

최근 자바스크립트 문법에 발맞추어
jquery Ajax 도 프로미스(Promise) 방식의 코딩 패턴을 지원하는 사실을 알게 되었는데요.

몇 버전부터 지원되는지는 알 수 없으나, 3.6.0 버전에서는 확실히 지원되는 것으로 확인됩니다.
우선 결과소스를 먼저 확인시켜드리겠습니다.

json 결과를 반환해줄 node.js 서버 소스를 아래와 같이 구성하고,

const express=require('express');
const bodyParser = require('body-parser');
const app=express();

app.use(express.static('public'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended : true}));

app.post('/samplejson', function(req,res) {
	res.json({
		result: req.body.msg + " feedback!"
	});
});

app.listen(8080, function() {});


public/sample.html 소스를 아래와 같이 구성합니다.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>jQuery 프로미스</title>
  </head>  
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <script>
    $.ajaxSetup({ type: 'post', dataType: 'json' });
    async function go(){
        try {
            result = await $.ajax({
                url: '/samplejson', 
                data: { msg: "안녕" } 
            });
            console.log(result); //  성공일 때 처리
        } catch(error){
            console.log(error);  // 오류일 때 처리
     }
    }  
  </script>
  <body>	
	<input type=button value="메시지테스트" onclick="go()">
  </body>
</html>


node  서버를 작동하고, 웹페이지를 띄워 버튼을 클릭하면,

콘솔창에 아래와 같은 결과가 출력되는데요.

jQuery 함수가 웹을 호출한 다음 받아온 json 결과값을 콘솔창에 출력하기 때문입니다.

소스를 잠깐 설명드리자면 프로미스에서 await 방식 처리를 위해서는
반드시 async 방식으로 함수가 선언되어야 하는 것은 당연하고,

async function go(){
    :
}


요새 유행하는 방식의 await 방식으로 jquery 도 사용이 가능합니다. 아래는 그 코드인데요.
jQuery 는 Ajax 에 대해 아주 간결하게 get이나 post 전송이 가능합니다.

result = await $.ajax({
    url: '/samplejson', 
    data: { msg: "안녕" } 
});


원래대로라면 이 안에 post 로 호출할지, 또는 json 형식으로 값을 받을 것인지를 함께 적어주어야 하나,
스크립트 도입부분에 아래 스크립트를 한번만 지정해 주면 이후로 모든 ajax 호출의 기본값으로 이 값이 적용됩니다.

$.ajaxSetup({ type: 'post', dataType: 'json' });

만약 json 이 아니고 HTML 로 결과를 받으려면 dataType 에 'text/html' 을 적어주면 되지요.

ajax 함수의 실행이 끝난 다음, result 에는 그 결과값이 반환되는데요.
이어서 다음 코드에 이어서 그 값으로 처리를 하면 됩니다.
success 와 같은 콜백 함수 정의도 필요가 없으므로 오히려 과거의  jQuery ajax 보다 훨씬 편리해졌습니다.

console.log(result); //  성공일 때 처리

만일 에러 처리가 필요하다면, try ~ catch 문을 이용하여 아래와 같이 오류 처리도 가능합니다.
매우 간단하지요? :)

try {
    result = await $.ajax({
        url: '/samplejson', 
        data: { msg: "안녕" } 
    });
    console.log(result); //  성공일 때 처리
} catch(error){
    console.log(error);  // 오류일 때 처리
}


위 방식 외에도 프로미스의 then ~ catch 방식 또한 사용이 가능하지만
최신 jQuery 버전에서 확인결과 아래 방식은 오류가 발생합니다.
jQuery 버전을 앞으로 올릴 예정이 있다면 await 방식이 권고됩니다.

$.ajax({
    url: '/samplejson', 
    data: { msg: "안녕" }
})
.then((result) => {
    console.log(result);
})
.catch((err) => {
   console.log(err);
});