[Vuejs] Array를 활용한 Service 순차 동기 호출

Jinbro·2022년 1월 26일
0

Vuejs

목록 보기
2/9

다수의 Service를 동기적으로 호출해야 하는 경우, Array를 활용하면 유연한 구조를 설계할 수 있다.

Service Array 초기화 함수 선언

  • svId : Service ID
  • svDv : Service 구분
  • call : Service 호출
initSvList() {
      this.svList = [
        {
          svId: 'initPage',
          svDv: 'init',
          call: async () => {
            await this.initPage();
          },
        },
        {
          svId: 'callFunc1',
          svDv: 'call',
          call: async () => {
            await this.callFunc1();
          },
        },
        {
          svId: 'callFunc2',
          svDv: 'call',
          call: async () => {
            await this.callFunc2();
          },
        },
      ];
      this.callSvList(this.svList); // Service 호출
    },

Service 동기 순차 함수 선언

  • async : 해당 함수는 항상 Promise 객체 반환
  • await : Promise 가 완료될 때까지 대기
async callSvList(list) {
      for (const it of list) {
        console.log(`${it.svId} start!`);
        await it.call();
      }
    },
  • console log
initPage start!
callFunc1 start!
callFunc2 start!

특정 Service 호출

  • filter를 활용하여 조건에 맞는 Service만 호출
// svId 가 'callFunc2' 인 Service만 호출
const onlyCallFunc2SvList = this.svList.filter(sv => sv?.svId === 'callFunc2');
this.callSvList(onlyCallFunc2SvList);

// svDv 가 'init' 인 Service만 호출
const onlyInitSvList = this.svList.filter(sv => sv?.svDv === 'init');
this.callSvList(onlyInitSvList);

Service 예외처리

  • Service에 대한 breakPoint, validation 체크를 유연하게 설정할 수 있다.
{
  svId: 'exceptionSample',
  scDv: 'call',
  call: async () => {
    await this.callExceptionSample(); 
  }
  breakPoint: () => {
    return this.isBreakPoint();
  },
  validate () => {
    return this.isValidate();
  },
}
  • sample (breakPoint, validate 적용)
async callSvList(list) {
      for (const it of list) {
        if (it?.breakPoint && it?.breakPoint()) {
          break; 
        }
        await it.call();
        if (it?.validate && it?.validate()) {
          await it.call();
        }
      }
    },
profile
자기 개발 기록 저장소

0개의 댓글