new Promise(응용)3

new Promise & ajax 사용하기

 <script>
    (function(){
        var a, b, c;
        // Promise 정의1
        var fileA = function(){
            var pr = new Promise(function(resolve, reject){
                $.ajax('a.json').done(function(response){
                    resolve(response);
                }).fail(function(){
                    reject('파일 읽어오기 에러 메시지');
                });
            });
            return pr;
        }
        // Promise 정의2
        var fileB = function(){
            var pr = new Promise(function(resolve, reject){
                $.ajax('b.json').done(function(response){
                    resolve(response);
                }).fail(function(){
                    reject('파일 읽어오기 에러 메시지');
                });
            });
            return pr;
        }

        // Promise 정의3
        var fileC = function() {
            var pr = new Promise(function(resolve, reject){
                $.ajax('c.json').done(function(response){
                    resolve(response);
                }).fail(function(){
                    reject('파일 읽어오기 에러 메시지');
                });
            });
            return pr;
        }

        //위에서 정의한 내용이 Promise 수행이 되고 나서(then) 실행을 한다.
        fileA().then(function(data){
            a = data;
            console.log(a);             //response 값 출력
            return fileB();             //위에서 정의한 2번째 Promise를 의미한다.
        }).then(function(data){
            b = data;
            console.log(a[0].price + b[0].price);         //response 값 출력
            return fileC();             //위에서 정의한 3번째 Promise를 의미한다.
        }).then(function(data){
            c = data;
            console.log(a[0].price + b[0].price  + c[0].price );     //response 값 출력
        }).catch(function(error){
            console.log('then error : ', error);   // Error 출력
        });
    })();
</script>
// a.json
[
	{
        "id":1,
        "name": "Mocade",
        "price": 350,
        "img":"images/TRAINERS1.jpg",
        "title":"Black Mocade",
        "text":"Hey look up! It's a plane! No, It's a bird! No, it's the assassin performing leap of faith."
    },
    {
        "id":2,
        "name":"zipper",
        "price":59,
        "img":"images/TRAINERS1.jpg",
        "title":"No zipper dress",
		    "text":"The price of this dress has been cut off since we lost the zipper on the back."
    },
    {
        "id":3,
        "name":"ernest",
        "price":299,
        "img":"images/TRAINERS1.jpg",
        "title":"Dear Ernest",
		    "text":"We'll bring readers to the edge of ther seats and keep them there until we sell this dress."
    }
]

Last updated