-
항해 99 5기 TIL_14항해 99 2022. 1. 23. 19:35
▶ Today I Learned
<Promise 함수>
자바스크립트에서 비동기처리를 동기로 처리할 수 있게 돕는 객체 유형,
[왜 Promise를 쓰려는 걸까?]
$.get('url 주소', function(response) { // ... });
와 같은 형태로 데이터를 받아와서 표시하려 하는데 데이터가 다 받아지기도 전에 데이터를 화면에 표시하는 기능이 작동해버리면
빈화면이 뜨거나 오류가 뜰 확률이 높음 -> 이러한 비동기처리를 방지하기 위해 Promise를 사용
프로미스는 resolve가 실행되어야 그 다음인 then()으로 넘어가며 거부인 reject 발생 시 catch()라는 오류를 띄어주는 구문으로 넘어감
프로미스(약속)이라는 건 미래의 어느 시점에 결과를 제공하겠다고 '약속'하기 때문
출처: https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Promise
형태는 다음과 같음
new Promise(executor); // When Promise takes place, executor will be automatically executed. // the 'firstPromise.then(...)' would not be run unless the function 'resolve' is called // from the 'executor' section. new Promise((resolve, reject) => { // 명령문은 여기다가 사용 });
여기서 executor에는 함수만 올 수 있고 보통 인자로 resolve, reject가 주입됨
프로미스는 대기, 이행, 거부라는 3가지 상태로 나뉘며 연산 성공 시 이행, 연산 실패 시 거부됨
오류 처리시에는 catch()구문을 쓸 것, then()의 두번째 인자로 오류를 주어도 되지만 그렇게되면 Uncaught (in promise) error(then()의 첫번째 콜백함수에서 오류를 감지해내지 못함)가 발생함
<콜백 함수 callbackfn>
특정 로직이 끝났을 때 (ex: response라는 데이터가 준비되었을 때) 사용자가 원하는 동작을 수행할 수 있게 해주는 함수.
콜백 함수로도 비동기처리를 동기 처리로 제어해줄 수 있지만 좀 Promise가 좀 더 유용하다고 함 (확실히 보기에도 Promise가 더 직관적)
<비동기 함수 async>
비동기처리: 특정 코드의 실행이 끝날 때 까지 멈추지 않고 다음 코드가 실행되는 것, 식당에 빈자리가 있을 때 사람들이 다음 사람이 나갈 때 까지 기다리지 않고 자유롭게 들어와 밥먹고 나가는 것과 유사함.
async & await: 기존 콜백함수와 프로미스 방식의 단점을 보완하고자 최근에 나온 개념
이 방법을 사용하면 코드의 가독성이 높아지고 기존 위 두 가지 방식을 고려할 필요가 없음
왜 가독성이 높은 가?
예를 들면
let info = { name: 'Kim' height: 180, }; if (info.name === 'Kim') { console.log(info.height); // 180 }
와 같이 코드는 위에서 부터 아래로 읽어가며 '변수가 선언됐고 해당 변수가 객체가 이러면 콘솔에 로그를 찍고...'와 같이 이해하는 게
대부분 자연스러울 것이다.
여기서 async와 await을 쓰자면
async function infoCheck() { let info = await fetchInfo('domain.com/info/1'); if (info.name === 'Kim') { console.log(info.height); } }
이렇게 된다.
즉, 가독성 좋은 코드의 구조를 그대로 유지하면서 비동기처리의 문제(info라는 데이터를 받아와서 info에 넣어주기도 전에 if 문을 처리해버리는 오류)를 해결해줄 수 있다.
여기서 중요한 점은 await 뒤에 나오는 메서드가 반드시 Promise형태의 객체를 반환해주어야 한다는 것이다.
프로미스 객체가 반환될 때까지 await(~을 기다리다), 기다려서 값이 반환되면 그 다음 코드를 실행해주는 것임
출처: https://joshua1988.github.io/web-development/javascript/js-async-await/
스파르타 코딩클럽 Node.js 기초 강의
cf) fetch()라는 구문은 최신 버전의 브라우저들에서 사용가능하다고 함
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API 참조
▶ 느낀 점
처음엔 비동기처리, 콜백함수, 프로미스 같은 것들이 다소 어렵게 느껴졌다. 그렇지만 이렇게 구글링해서 필요한 정보를 찾아보고
다시 하나하나 코드를 읽어가며 이해하려고 노력하니 확실히 틀이 잡히는 것 같다. 물론 아직도 완전히 이해한 것은 아니지만
이제 실제로 사용해보면서 사고하고 필요한 정보를 더욱 참고한다면 할 수 있을 거라 믿는다.
내일도 화이팅 :)
▶ 공부 시 참고 링크들
https://joshua1988.github.io/web-development/javascript/javascript-asynchronous-operation/
https://joshua1988.github.io/web-development/javascript/promise-for-beginners/
https://joshua1988.github.io/web-development/javascript/js-async-await/
'항해 99' 카테고리의 다른 글
항해 99 5기 TIL_15 (0) 2022.01.25 항해 99 5기 WIL_2 (0) 2022.01.23 항해 99 5기 TIL_13 (0) 2022.01.22 항해 99 5기 TIL_12 (0) 2022.01.22 항해 99 5기 TIL_11 (0) 2022.01.21