I am maker

ESLint: Promise executor functions should not be async.(no-async-promise-executor) 본문

ESLint: Promise executor functions should not be async.(no-async-promise-executor)

코딩하는고릴라 2023. 2. 22. 20:09
반응형

ESLint: Promise executor functions should not be async.(no-async-promise-executor)

 

뜻 : 프로미스 실행자함수들은 비동기이면 안됩니다.

아마도 promise 내에 Promise.resolve 등의 static 함수를 사용하는 경우 어떤 promise가 종료되었는지 알 수 없기 때문인 것 같습니다.

 

 

보통은 이런 에러자체를 접하지 않을텐데,

구닥다리 콜백 함수를 감싸서 비동기로 해주는 경우에 나타날 수 있습니다.

 

 

언제 나타나는지, 어떻게 해결하는지 같이 해보시죠

 

우선 구닥다리 콜백함수를 하나 만들어보겠습니다.

// 콜백 함수
function callBackFunction(callback, param){
 setTimeout(()=>{
   callback(param+1)
 },1000);
}

 

이 함수는 param이라는 파라미터를 받아서 1을 더한 후 1초뒤에 callback을 실행시키는 함수입니다.

예전 async 패턴의 문법이 없었을 때에 많이 쓰던 콜백함수입니다.

콜백지옥!

 

 

그리고 이 콜백함수를 비동기로 호출해서 감싸주는 코드를 만들어보겠습니다.

asyncFunctionMan이라고 만들게요

// 비동기 함수
export async function asyncFunctionMan() {
  return new Promise((resolve, reject) => {
    try{
        callBackFunction(
         function(result){
           resolve(result)
         }, 1
        );
    }catch(e){
		reject(e);
	}
  });
}

이렇게 하면 구닥다리 콜백함수를 async await로 쓸 수 있게끔 바꿔줄 수 있습니다.

문제는 이 함수내에서 또 비동기 코드를 사용해야하는 경우입니다.

아래 코드를 보시면 asyncFunctionChild라는 가상의 비동기 함수를 실행해서 기다린다고 해보겠습니다.

그러면 await를 써야하는데 await를 하려면 async function이어야하고

Promise를 실행하는 함수가 async가 되어 문제가 발생합니다

// 비동기 함수
export async function asyncFunctionMan() {
//11111 아래줄 문제의 async
  return new Promise(async (resolve, reject) => {
    try{
    // childResult 를 조회해오는 코드가 비동기 함수인경우
    // 이를 기다렸다가, 해야하기 때문에 위 4번 라인에 async가 들어가게 됩니다.
        const childResult = await asyncFunctionChild();

        callBackFunction(
         function(result){
           resolve(result)
         }, childResult
        );
    }catch(e){
		reject(e);
	}
  });
}

 

 

해결방법

1. childResult를 상단으로 빼서 기다린다.

// 해결방법 1
export async function asyncFunctionMan() {
  const childResult = await asyncFunctionChild();
  return new Promise((resolve, reject) => {
    try{
        callBackFunction(
         function(result){
           resolve(result)
         }, childResult
        );
    }catch(e){
		reject(e);
	}
  });
}

2. asyncFunctionChild.then 을 사용해서 async를 쓰지 않는다.

// 해결방법 2
export async function asyncFunctionMan() {
  return new Promise((resolve, reject) => {
    try{
    	asyncFunctionChild().then(childResult=>{
            callBackFunction(
             function(result){
               resolve(result)
             }, childResult);
         });
    }catch(e){
		reject(e);
	}
  });
}

 

반응형