알쓸전컴(알아두면 쓸모있는 전자 컴퓨터)

javascirpt 비동기 처리를 위한 promise 사용법 본문

Web /Vue js tip

javascirpt 비동기 처리를 위한 promise 사용법

백곳 2018. 3. 30. 11:25

promise 사용법



promise 사용법은 인터넷어 많이 나와 있습니다만 


제 기준으로 좀더 쉽게 이해 하기 위해 작성 하였습니다. 


promise 는 비동기 처리를 순서 대로 실행 시키키 위한 기능 입니다. 


기존에 promise가 없기전에는 


함수에 콜백 -> 콜백 ->콜백 ...... 


이런 형식이여서 코드의 가독성과 유지보수가 힘듭니다.


그래서 나온것이 promise 입니다. 


IE11 에서는 promise polliy-fill 이 필요합니다. 

 


<script>
methods : {
get_machine_list(){
var _this = this;
return new Promise(function(resolve, reject){
axios.post('/W_Server/oisystem_get_machine_table')
.then((r)=>{
setTimeout(() => {
console.log(r.data);
_this.machine_list = r.data;
resolve('1');
},2000);
})
})
},test_func1(){
return new Promise(function(resolve, reject){
setTimeout(() => {
console.log("test2");
resolve('1');
},2000);
})
}
,test_promise(){
var _this = this;
this.get_machine_list()
.then(function() { return _this.test_func1()})
.then((e)=>{
console.log('test3');
})
}
}

</script>



위와 같이 작성 하면 됩니다. 


여기서 


var _this = this; 


는 Promise 안에서 this 을 인식 하지 못합니다


또는 


select_oi_machine_list(){
return new Promise(function(resolve, reject){
axios.post('/W_Server/oi_system/select_oi_machine_list').then(r=>{

console.log(this);
resolve(r.data);
})
}.bind(this))
}



bind 를 사용 하여 this 를 사용 해도 됩니다. 


위와 같은 방식으로 사용을 했습니다. 


이벤트 등에 test_promise 을 등록 시키고 


함수를 실행 시키면 



위와 같이 나옵니다. 


여기서 


resolve('1');


이 실행 되야 다음 then 으로 이동합니다. 


resolve  함수가 는 성공 할때 


reject 는 함수가 실패 할때 등으로 사용 됩니다. 


위의 resolve,reject  둘 중 1개가 있어야 다음 then 으로 넘어갑니다. 


그리고 파라메터로 넘겨주는 값은 then( e=>{} ) 같이 e로 변수를 받을수 있습니다.  






Comments