Project

Javascript API, 비동기 객체에서 Promise 객체가 나올때

Atriel 2024. 4. 5. 22:51

 

const getData = async() => { 
    try{
        const res = await fetch("https://tarkov-time.adam.id.au/api");
        const data = await res.json();
        var json = JSON.stringify(data);
        var obj = JSON.parse(json);
        return obj.left;
    } catch (error) {
        console.log(`error : ${error}`);
    }
};
console.log(getData());

 

몇시간을 땅바닥에 내던진 채로 해결했다.

엉뚱한걸 검색하다 구경하느라 시간을 많이 소모함

 

위 코드로 api를 당겨오면

내가 원하는 time데이터가 아닌

 

Promise 객체가 나오게 되는데

async로 비동기적으로 가져온 데이터가 Promise 객체를 반환해서 그렇다

 

Promise는 Javascript에서 비동기 처리에 사용되는 객체로 

3가지 상태가 있따

Pending : 비동기 처리 이전

Fulfilled : 비동기 처리 성공적으로 완료

Rejected: 비동기 처리 실패

 

 * try catch를 이용해 Rejected 상태에 대한 에러처리를 할 수 있다.

 

데이터는 fulfilled로 잘 땅겨져 와있고

 

데이터를 받을때 그냥 getData()함수로 받는게 아니라 받는쪽에도

async, await 처리를 하니 원하는 데이터가 추출됨

 

async, await을 사용할땐 항상 try catch 처리를 해줘야 한다 해서 양쪽다 해줬다.

+ getData에서 했던 불필요한 과정들(시도들) 삭제

 

const getData = async() => { 
    try{
        const res = await fetch("https://tarkov-time.adam.id.au/api");
        const data = await res.json();
        return data.left;
    } catch (error) {
        console.log(`error : ${error}`);
    }
};

(async () => {
    try{
        let data = await getData();
        console.log(data);
    } catch(e){
        console.log(e)
    }
})();

 

잘 땡겨와짐

 

 

 

완성된 기능 코드 (API에서 한번 데이터를 받아온뒤 1초에 7초씩 증가하게 무한반복

(게임 시간이 현실보다 7배 빠르다)

function init(data) {
	(async () => {
		try{
			let secs = 1000;

			now = await getData();
			date = new Date('2024-04-06 ' + now)
			console.log(date);

			let count = 0;
			setInterval(function update_time() {
				try{
					date.setTime(date.getTime() + secs)

					var hh = date.getHours();
					hh = hh >= 10 ? '' + hh : '0' + hh;
					var mm = date.getMinutes();
					mm = mm >= 10 ? '' + mm : '0' + mm;
					var ss = date.getSeconds();
					ss = ss >= 10 ? '' + ss : '0' + ss;
	
					digits.h1.attr('class', digit_to_name[hh[0]]);
					digits.h2.attr('class', digit_to_name[hh[1]]);
					digits.m1.attr('class', digit_to_name[mm[0]]);
					digits.m2.attr('class', digit_to_name[mm[1]]);
					digits.s1.attr('class', digit_to_name[ss[0]]);
					digits.s2.attr('class', digit_to_name[ss[1]]);
				} catch(e){
					console.log(e)
				}
		},1000/7);
		} catch(e){
			console.log(e)
		}
	})();
};

init();

추가적으로 setInterval이 익숙하지 않아 시간을 또 많이 버림

자바스크립트는 많이 써보면서 익숙해져야 할꺼 같다