-
22.[React 팀과제 정리] Promise , TDZ, ThunkJava Script & Type Script 2023. 1. 9. 23:10728x90
Thunk
리덕스에서 dispatch를 하면 action이 리듀서로 전달이 되고, 리듀서는 새로운 State를 반환하는데, 이 중간에 미들웨어를 넣어서 원하는 작업을 중간에 실행할 수 있다.
미들웨어로 가장 많이 이용되고 있는 방식이 redux Thunk이다.
Thunk의 핵심은 객체가 아닌, 함수를 dispatch할 수 있게 해준다는 것이다.
리덕스 툴킷에서 thunk함수를 생성할 땐, **createAsyncThunk()**를 통해 생성하며, 첫번째 자리에는 action value, 두 번째 자리에는 함수가 들어간다.
🔐 프로미스는 정확히 말하면 비동기가 아닙니다. 비동기와 프로미스는 각각 무엇일까요?
🐹 동기와 비동기의 차이
동기 Synchronous : 요청 후 응답을 받아야 다음 동작 실행.
비동기 Asynchronous : 요청 보낸 후 응답과 관계없이 다음 동작 실행
JS는 단일 스레드 프로그래밍 언어로, 단일 호출 스택이 있어 한번에 하나의 일을 처리하는 동기 방식이다.
비동기적 처리는 흐름이 멈추지 않기 때문에 동시에 여러가지 작업을 처리할 수도 있고, 기다리는 과정에서 다른 함수를 호출할 수도 있다.
🐹 Promise를 쓰는 이유
작업이 끝나야 그 다음 예정된 작업을 할 수 있는 동기적 처리방식에서는 하나의 함수를 처리하는데 오랜 시간이 걸린다면 다음 실행할 함수에 지장을 줄 수 있다는 문제점이 발생한다.
Java script에서 이러한 문제점을 보완하기 위해 비동기를 구현하는 방법 중 하나가 Promise.
🐹 Promise에 대하여
Promise는 ES6에서 비동기처리를 다루기 위해 사용되는 객체이다.
비동기적으로 실행하는 작업의 결과 (성공과 실패)를 나타내는 객체이다. 비동기처리의 결과를 객체화한다는 것이 특징이다.
new Promise()를 통해 프로미스를 생성하고 resolve, reject함수를 인자로 받는 함수가 생성자의 함수의 인자 자리에 들어간다. promise객체는 종료될 때까지 3가지 상태를 갖는다.
Pending(대기) : 비동기 처리 로직이 아직 완료되지 않은 상태 fulfilled(이행) : 비동기 처리가 완료되어 프로미스가 결과 값을 반환해준 상태 Rejected(실패) : 비동기 처리가 실패하거나 오류가 발생한 상태
프로미스 처리 흐름 - 출처: MDN
function getData() { return new Promise(function(resolve, reject) { $.get('url', function(response) { if (response) { resolve(response); } reject(new Error("Request is failed")); }); }); } // 위 $.get() 호출 결과에 따라 'response' 또는 'Error' 출력 getData().then(function(data) { console.log(data);// response 값 출력 }).catch(function(err) { console.error(err);// Error 출력 });
서버에서 제대로 응답을 받아오면 resolve()메서드를 호출, 응답이없으면 reject()메서드를 호출한다.
호출된 메서드에 따라 **then()**이나 **catch()**로 분기하여 응답결과 또는 오류를 출력할 수도 있다.
이처럼, then()과 catch() 문을 체이닝을 통해 비동기 로직의 성공/실패 여부에 따라 분기 처리가 가능하다.
🔐 TDZ(Temporal Dead Zone/일시적 사각지대)란?
TDZ :변수가 선언되고 초기화되기까지의 그 사이에 위치하는 사각지대
var변수선언과 const, let 변수선언으로 나누어 알아보자.
🐹 var는 변수 선언 전에 선언단계와 초기화단계를 동시에 실행한다.
선언과 초기화가 동시에 실행되기 때문에 실행 컨텍스트 변수 객체를 등록 후 바로 그 메모리를 undefined한다.
var는 TDZ가 존재하지 않기 때문에 호이스팅이 일어난다.
❓호이스팅이 뭐더라…?
https://velog.io/@yeonlisa/Hoisting이란
🐹 let과 const는 선언단계와 초기화단계가 분리되어 실행된다.
그래서 선언단계와 초기화단계 사이에서는 실행컨텍스트를 변수에 등록했지만 메모리가 할당되지 않은 상태라 *‘reference error’*가 발생한다. 이러한 사각지대가 TDZ(Temporal Dead Zone)이다.
function function1() { console.log('your name?', yourname); var yourname = 'Lee Chae Jung'; }
function1 함수 스코프 내에서 yourname변수가 선언되기 전에 참조했기 때문에 TDZ의 에러가 발생해야하지만 var로 선언한 변수가 호이스팅되어 에러가 발생하지 않고 undefined가 표기됨.
function function2() { console.log('your name?', yourname); let yourname = 'Lee Chae Jung'; }
function2 함수 스코프 내에서 let으로 선언된 yourname변수가 선언은 되었지만 값이 초기화되기 전에 yourname변수를 사용하려했기 때문에 TDZ의 위치에서 에러 발생.
728x90'Java Script & Type Script' 카테고리의 다른 글
24. Immer라이브러리와 불변성 관리 (0) 2023.01.11 23.[리액트] 리덕스 툴킷, JSON 서버, 콜백 함수로 비동기 처리 방식의 문제점 해결하기, PROMISE (0) 2023.01.11 21.[React, JS] JS 비동기처리와 Promise, async, await (0) 2023.01.07 20. [Java Script] 이벤트 발생 객체, 입력방식에 따른 이벤트, input 값 비우기, input 공란이면 이벤트 막기, 삭제버튼 구현, JS로 Todo List만들기 (0) 2023.01.06 19. [리액트] 리액트 리덕스를 활용한 todo List 과제 진행상황 (0) 2023.01.04