study

패스트캠퍼스 챌린지 42일차

swimKind 2022. 3. 6. 22:45

로그인 병렬 - 연속적 비동기 API 처리의 이해

 

로그인 처리를 하는 서버와의 통신에는 비동기 처리가 필요하다. 단순히 화면이 바뀌는 동작만이 아니라면 서버와의 통신간에 연결이 끊어질 수도 있고 다른 에러가 발생할 경우가 있기 때문에 비동기 처리를 이용한다.

 

하지만 이번 로그인 처리에선 2가지의 API를 병렬적으로 처리한다. 그렇게 데이터를 받기 위해서 axios 라이브러리를 사용한다. axios에서 지원하는 메소드중에 all 메소드를 통해 2가지의 API 데이터를 받아서 두가지의 서버 비동기 처리를 한 후에 완료 후에 데이터를 반환 받아서 사용한다.

 

import template from './login.template';
import TextField from '../views/text-field';
import axios  from 'axios';

export default class Login {
  #template = template;
  #data;
  #container;
  #loginFail = false;
  #fields = [];

  constructor(container, data) {
    this.#container = document.querySelector(container);
    this.#data = data;

    this.#initialize();
  }

  #initialize = () => {
    ...
  }

  #onSubmit = e => {
    e.preventDefault();

    const loginData = this.#fields
      .map(field => ({ [field.name]: field.value }))
      .reduce((a, b) => ({ ...a, ...b }), {});

    axios.post('/api/authentication', loginData)
      .then(result => {
        return result.data.result;
      })
      .then(({ id, token }) => {
        const options = { headers: { token } };
        this.#data.store.token = token;

        return axios.all([
          axios.get(`/api/user/${id}`, options),
          axios.get(`/api/user/${id}/posts`, options),
        ]);
      })
      .then(([profile, posts]) => {
        this.#data.store.userProfile = profile.data.result;
        this.#data.store.userPosts = posts.data.results;

        location.href = '/#/profile';
      })
      .catch(error => {      
        this.#loginFail = true;
        this.render();
      });
  }

  render = () => {
    ...
  }
}

#onSubmit 메소드를 실행하게되면 고유의 submit 메소드의 동작은 막는다. 기존의 submit 기능은 페이지의 전환이 일어나는데 페이지의 이동을 막기 위해 사용한다. fields 배열에 데이터를 배열로 해당하는 데이터는 Promise 패턴을 이용해서 then의 실행이 완료 될때마다 Promise를 반환하는 형식이다. 

 

 

 

 

https://bit.ly/37BpXiC

 

패스트캠퍼스 [직장인 실무교육]

프로그래밍, 영상편집, UX/UI, 마케팅, 데이터 분석, 엑셀강의, The RED, 국비지원, 기업교육, 서비스 제공.

fastcampus.co.kr

 

본 포스팅은 패스트캠퍼스 환급 챌린지 참여를 위해 작성되었습니다.

 

#패스트캠퍼스 #패캠챌린지 #직장인인강 #직장인자기계발 #패스트캠퍼스후기 #김민태의프론트엔드아카데미:제1강JavaScript&TypeScriptEssential