PostIT

[Javascript/Ajax] JavaScript에서의 변수 담아내기 - async(동기 Ajax) 본문

Script/JavaScript

[Javascript/Ajax] JavaScript에서의 변수 담아내기 - async(동기 Ajax)

shun10114 2017. 3. 6. 16:06

# Ajax에서의 async로 해결, 하지만 또 다른 문제의 발생


최근 수정일 : 2017.04.18

## 1. 배경

1차

Stomp를 이용한 비동기 통신 Message를 주고받는 과정에서 Message데이터를 Bootstrap Popover에 값을 넣어주는 부분에서 비동기 데이터를 가져오지 못하는 문제가 발생되었다. 이부분을 해소하기 위해 Ajax 통신의 비동기를 false로 해주어 문제를 해결하였다.


이 상황의 소스코드를 보면 아래와 같다.

/* content 부분에서 getMessageList 호출 */
var $popover=$('#openPopover').popover({

    placement: 'bottom',

    template: '<div class="alertPopOver popover"><div class="popover-title"></div><div class="popover-content" id="popover-content"></div></div></div>',

    html: '알림창',

    title : '<span class="text-info font-18b">알림창</span>'+

            '<span><a href="/tunner/message/list"><button type="button" class="btn-u btn-u-blue rounded margin-left-10">전체 보기</button></a></span>'+

            '<button type="button" id="closePopover" class="close">&times;</button>',

    content : MessageModule.getMessageList()

}).on('shown.bs.popover', function () {

    var $popup = $(this);

    $(this).next('.popover').find('button.close').click(function (e) {

        $popup.popover('hide');

    });

})


/*private Method*/

var _getMessageList = function (callback){

    var ajaxResult=null;

    $.ajax({

        /* 비동기 통신 여부  */

        async : false, 

        global : false,

        type : "GET",

        url : "/tunner/message/from/user",

        success : function(data) {

            console.log('Success');

            ajaxResult=data;

        },

        error : function(e) {

            console.log('Error');

        }

    })

    return ajaxResult;

};

    

2차

1차에 과정으로 문제를 해결하면, console 창에 이러한 에러메세지를 볼 수 있다.
'Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check https://xhr.spec.whatwg.org/.'
XMLHttpReqeust(ajax) 통신을 동기화로 운영하면 End User에게 좋지 않은 경험을 줄 수 있어 더 이상 지원하지 않는다. 라는 내용이다.

이를 해결하기 위해서는 
Javascript의 Promise()를 사용하는 것이 하나의 해결책이라고 생각한다.




##. 해결책

https://promisesaplus.com/

http://stackoverflow.com/questions/5316697/jquery-return-data-after-ajax-call-success


위 사이트를 참고하면 큰 도움이 될 것으로 생각합니다. 

그리고, 시간이 될 때, Promise()로 구현한 Javascript를 올리도록 하겠습니다.


Comments