티스토리 뷰

요약

Vue에서 Ajax Call을 하는 경우 Promise가 타는 구간을 잘 살필 것

data(){
	return {
    	info:[]
    }
},
methods:{
    call_api(url, callback){
      fetch(url)
        .then(res=>{
          console.log('res',res)
          return res.json()
      })
      .then(data=>{
         callback(data)
      })
},
created() {
	const url = 'http://hello.com/api/info'
	call_api(url, data=>{
	    this.info = data    	
	})
}

이렇게 created에서 ajax call을 하고 그 결과를 info에 바인딩 하는 코드는 여기까지는 문제가 없습니다.

 

문제가 발생할 만한 코드

data(){
	return {
    	info:[],
        info2:[]
    }
},
methods:{
    call_api(url, callback){
      fetch(url)
        .then(res=>{
          console.log('res',res)
          return res.json()
      })
      .then(data=>{
         callback(data)
      })
},
created() {
    const url = 'http://hello.com/api/info'
    call_api(url, data=>{
		this.info = data    	
    })
    const url2 = 'http://hello.com/api/info2'
    call_api(url2, data=>{
        this.info2 = data    	
    })
}

위와 같이 데이터를 여러번 불러 오는 경우는 문제가 생길 수 있습니다. 위 코드는 첫번째 데이터를 불러오고 두번째 데이터도 불러옵니다. 하지만 created에서 다른 작업을 추가로 하는 경우는 데이터가 호출 되기 전에 다른 코드가 탈 수 있습니다.

 

 

 

created() {
    const url = 'http://hello.com/api/info'
    call_api(url, data=>{
		this.info = data    	
    })
    const url2 = 'http://hello.com/api/info2'
    call_api(url2, data=>{
        this.info2 = data    	
    })
    
    this.info = this.info.map(item=>item * 10)
}​

위 코드에서 info에 *10을 하는 코드를 추가 하였는데요. 우리가 봤을때는 순서대로 탈 것 같지만 그렇지 않습니다. ajax콜이 네트웍을 타고 오기 때문에 this.info = ~~~ map( item = ~~~) 이 코드가 가장 먼저 실행이 될 수 있습니다.

 

created() {
    const url = 'http://hello.com/api/info'
    const url2 = 'http://hello.com/api/info2'
    call_api(url, data=>{
        this.info = data    	
        call_api(url2, data=>{
        	this.info2 = data    	
            this.info = this.info.map(item=>item * 10)
    	})
    })
}

그래서 실행 순서를 보장 하고 싶다면 이렇게 이벤트를 체인처럼 엮어주어야 합니다.

 

end.

공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함