[Javascript] 비동기 함수, Promise, then, async, await 예제
//--------------------------------------
//then을 이용해 순차적으로 덧셈
function proc1(arg1){
console.log('proc1 - 0', arg1);
fnPromise(1, 10)
.then( ret => { //resolve
console.log('then -1', ret); return ret;
})
.then( ret => {
ret++; console.log('then -2',ret); return ret;
})
.then( ret => {
ret++; console.log('then -3',ret); return ret;
})
.finally( ret => {
console.log('항상 호출- finally', ret);
})
.catch( ret => {
console.log('에러 -catch', ret);//reject
})
}
//----------------------------------
// async , await 사용
//비동기 함수를 여러번 호출, async
async function proc2(arg1){
console.log('proc2 - 0', arg1);
var ret = null;
try {
ret = await fnPromise(1, 10);
console.log('proc2 - 2', ret);
ret = await fnPromise(1, ret);
console.log('proc2 - 4', ret);
} catch(error){
console.log('proc2 - 에러', error);
}
}
//--------------------------------------
//기본 프라미스 함수(비동기)
function fnPromise(id, in1){
return new Promise( (resolve1, reject1) => {
setTimeout( function() {
console.log('fnPromise - 0', id, in1);
if( in1 !== false){
console.log('fnPromise - 1 - 성공', id, in1);
resolve1(in1+1);
}else{
console.log('fnPromise - 2 - 실패', id, in1);
reject1(in1);
}
},1000);
});
}
//------------------
$(function(){
proc2();
});