규도자 개발 블로그

[JavaScript/자바스크립트] InternetExplore에서 Promise쓰기 본문

HTML/CSS/JS/JavaScript

[JavaScript/자바스크립트] InternetExplore에서 Promise쓰기

규도자 (gyudoza) 2019. 10. 3. 01:34

[JavaScript/자바스크립트] InternetExplore에서 Promise쓰기

자바스크립트 해석기는 브라우저에 귀속돼있다. 그러니까 같은 코드라고 하더라도 IE에서 쓰는 해석기와 Chrome에서 쓰는 해석기가 달라 다르게 실행될 여지가 있다는 말이다. 이것을 크로스 브라우징 이슈라고 하는데 다르게 실행될 여지는 고사하더라도 아예 특정 함수는 Chrome에선 되지만 IE에선 실행조차 되지 않는 경우가 왕왕 있다. 그 중 하나가 바로 비동기처리를 깔끔하게 해주는 Promise이다.

 비동기처리는 요즘 웹서비스에 있어서 굉장히 흔하고 자주 일어나는 동작이기 때문에 가히 필수라고 할 수 있다. 그 비동기처리를 위한 코드를 깔끔하게 유지시켜주는 Promise객체를 IE에서는 사용하지 못한다. IE의 자바스크립트 해석기에는 기본적인 라이브러리에 Promise객체가 작성돼있지 않기 때문이다. 하지만 이래 코드를 추가하면 IE에서도 Promise를 사용할 수 있다.

<script type="text/javascript">
    if (typeof Promise !== "function") {
        document.write('<script src="https://cdnjs.cloudflare.com/ajax/libs/bluebird/3.3.5/bluebird.min.js"><\/script>');
    }
</script>

Promise객체를 사용하기 전에 해당 코드를 통해 라이브러리를 로드하면 된다. 이렇게 실험해볼 수 있다.

<!doctype html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
<script type="text/javascript">
    if (typeof Promise !== "function") {
        document.write('<script src="https://cdnjs.cloudflare.com/ajax/libs/bluebird/3.3.5/bluebird.min.js"><\/script>');
    }
</script>
<script>
    function promise1(param) {
        return new Promise(function (resolve, reject) {
            console.log(param + " as in promise function");
            setTimeout(function () {
                resolve(param + " as return");
            }, 1000);
        });
    }

    function promise2(param) {
        return new Promise(function (resolve, reject) {
            console.log(param + " as in promise function");
            resolve(param + " as return");
        });
    }

    promise1("this is promise1")
        .then(function (promise1response) {
            console.log("here is call");
            console.log(promise1response);
            return promise2("this is promise2")
        })
        .then(function (promise2response) {
            console.log("here is call");
            console.log(promise2response);
            return promise1("this is promise1's second call")
        })
        .then(function (promise1secondresponse) {
            console.log("here is call");
            console.log(promise1secondresponse);
        });
</script>
</body>
</html>

위 코드에서 라이브러리 로드하는 곳을 주석처리하고 IE에서 실행해보고, 다시 주석을 해제하고 실행해보면 한번에 와닿을 것이다.

 

Comments