ajax의 비동기 처리를 구현하는 방식 callback, Promise
//========
< 동기 처리 >
    - 시간이 많이 걸리는 함수도 무작정 대기 해야하는 문제
function square(x) {
    return x*x;
}
var number = square(2);
console.log(number);
출력 = 4
//===========
< 비동기 처리 >
    - 대기하지 않고 처리, 처리된후 나중에 결과값 반환
//=======
* 콜백함수로 비동기 처리
function square(x, callback) {
    setTimeout(callback, 1000, x*x);//1초후에 callback 함수가 호출 됨
}
 
var number = 0;
square(2, function(x) {
    number = x;
    console.log("결과 = ", number);
});
console.log("계산중...", number);
출력
계산중... 0
결과 = 4
//====================
* Promise로 비동기 처리
    - ajax를 구현하는 기술
// 예제 
//Promise 정의
var _promise = function (param) {
    return new Promise(function (resolve1, reject1) {
        // 비동기를 표현하기 위해 setTimeout 함수를 사용 
        window.setTimeout(function () {
            //작업 처리 ...
            
            if (param) {
                resolve1("해결 완료");
            } else {
                // 실패 
                reject1(Error("실패!!"));
            }
        }, 1000);
    });
};
//Promise 실행
_promise(true)
.then(function (text) {
    // 성공시
    console.log(text);
}, function (error) {  //에러 처리, then() 안에서 하는 방식
    // 실패시 
    console.error(error);
});
//=======================
// .catch() 로 에러 처리 예제
    - 에러 처리는 catch()로 하는 것을 권장
var _promise = function (param) {
    return new Promise(function (resolve1) {
        window.setTimeout(function () {
            //작업 처리 ...
            
            if (param) {
                resolve1("해결 완료");
            } else {
                // 실패 
                throw new Error("실패!!");
            }
        }, 1000);
    });
};
//=========
//Promise 실행
_promise(true)
.then(function (text) {
    // 성공시
    console.log(text);
}).catch( function (error) { // 에러 처리
    // 실패시 
    console.error(error);
});
//=========================
//Promise Channing 예제
    - .then()을 여러번 써서 순차적으로 결과 처리
//https://joshua1988.github.io/web-development/javascript/promise-for-beginners/
new Promise(function (resolve, reject) {
        setTimeout(function () {
            resolve(1);
        }, 1000);
    })
    .then(function (result) {
        console.log(result); // 1
        return result + 10;
    })
    .then(function (result) {
        console.log(result); // 11
        return result + 20;
    }); 
//===========================
* jQuery 에서 Promise
        //이전 jQuery의  ajax 처리 스타일
        /* $.ajax({
            url: '/jquery/ajax1.php?val1=val11',
            success: function (value) {
                var result = parseInt(value) + 10;
                setTimeout(function () {
                    console.log(result);
                }, 1000);
            }
        }); */
        //Promise 스타일
        /* $.ajax({
            url: '/jquery/ajax1.php?val1=val11'
        }).then(function (value) {
            return parseInt(value) + 10;
        }).then(
            delay(1000)
        ).then(function (result) {
            console.log(result);
        }).catch(function (error1){
            console.log("error1 = ", error1.statusText);
        }); */
//=============================
// 참고
https://beomy.tistory.com/10
https://joshua1988.github.io/web-development/javascript/javascript-asynchronous-operation/
https://joshua1988.github.io/web-development/javascript/promise-for-beginners/
https://programmingsummaries.tistory.com/325
'Code > JavaScript' 카테고리의 다른 글
| npm fsevents 경고 메시지 없애기 (1) | 2019.04.10 | 
|---|---|
| [Javascript] momentjs 사용법 (시간 다루기) (0) | 2019.04.01 | 
| jQuery 역사 (0) | 2019.01.28 | 
| [JavaScript] 이벤트 콜백 함수 와 this (0) | 2019.01.06 | 
| [JavaScript] 이벤트 위임(Event Delegation) (0) | 2019.01.05 | 










