티스토리 뷰

실습화면

이전 발행 글

HTML/CSS : 2022.06.15 - [WEB/Html & Css] - Bootstrap Basic

JS : 2022.06.15 - [WEB/JavaScript] - 타자게임 이벤트 처리 (basic)

 

이번 실습 링크

👍 실습 링크 1 (데이터상태처리)

👍 실습 링크 2 (API 연동)


데이터상태처리 (setInterval 사용하기)

🎈깃 링크로 setInterval 부분만 확인하기  ☜  COMMENT 확인하기

 

로직 확인하기

1. input에 이벤트 리스너를 넣고 input 이벤트가 발생하면 콜백함수가 실행되도록 한다.

2. 콜백함수로 (단어를 랜덤으로 바꿔주기 + 시간1초씩 감소) 하는 함수를 넣어준다.

  2-1. 1초씩 감소하는 setInterval의 콜백함수로 1초씩 감소하다가 값이 0이되면 게임이 종료되는 함수를 호출한다.

  2-2. 게임종료함수는 데이터를 초기화하는 기능을 넣는다.


API 연동

🎈깃 링크로 API연동 부분만 확인하기

 

CHECK POINTS

1. 구글링 => "random word api"

2. 주소창에  '현재주소+ 추가 url ' 입력 해서 데이터가 잘 받아와지는지 확인 

https://random-word-api.herokuapp.com/word?number=20 

3. Promise를 이용한 비동기 API 요청 함수 만들기

let isReady = false		// 비동기 API가 다 받아지면 코드가 실행되도록 도와주는 flag 변수이다.

init()

function init() {
  const res = fetch(API_URL)
  console.log(res) 		// Promise {<pending>} [PromiseResult]]: Response

  res
    .then(res => {
      console.log(res)		// Response
      console.log(res.json())	// Promise {<pending>} [[PromiseResult]]: Array(10)
      return res.json()
    })
    .then(data => {
      console.log(data)		// 최종 넘겨받은 데이터임.
      words = data.filter(item => item.length < 10)
    })
  isReady = true		// 단어가 다 받아지면 flag를 바꿔준다.
}
//==========================================================================
// Q. isReady 사용처?
// isReady는 flag(T/F)기능으로 true일 때만 실행되도록 만들 수 있다.
if (typedText.toUpperCase() === currentText.toUpperCase() && isReady) {
  addScore()
  setNewWord()
}

위의 fetch 부분을 줄인 코드

function init() {
   const res = fetch(API_URL)
     .then(res => res.json())
     .then(data => (words = data.filter(item => item.length < 10)))
}

 

4. Async / Await을 이용한 비동기 API 요청 함수 만들기

 

😏async function (비동기 함수) : callback과 promise의 단점을 보완하기 위해 추가됨

initWithAsync()

async function initWithAsync() {
  const res = await fetch(API_URL) 	// await을 붙이면 fetch가 다 완료된 다음에 다음 코드가 실행된다!
  const data = await res.json()		// console.log(data) // 동일한 데이터 10개가 들어간다.
  words = data.filter(item => item.length < 10)
}

실습파일

더보기

데이터상태처리 파일

testtest.html
0.00MB

API연동 파일

testtest.html
0.00MB

'WEB > JavaScript' 카테고리의 다른 글

[클린코드 For JS] 3. 타입  (0) 2022.06.27
[클린코드 For JS] 1. 소개 & 2. 변수  (0) 2022.06.27
타자게임 이벤트 처리 (basic)  (0) 2022.06.15
TODO Dom & Event  (0) 2022.06.14
[JS] HTTP API  (0) 2022.06.13
댓글
다크모드
Document description javascript psychology
더보기 ,제목1 태그 호버