ESLint: no-await-in-loop

김지훈·2022년 5월 30일
0
const commands = [];
const commandsPath = path.join(__dirname, 'commands');
const commandFiles = fs.readdirSync(commandsPath).filter((file) => file.endsWith('.ts'));

(async () => {
  for (let i = 0; i < commandFiles.length; i += 1) {
    const filePath = path.join(commandsPath, commandFiles[i]);
    const command = await import(filePath);
    commands.push(command.default.data.toJSON());
  }
})();

discord.js 예제를 보고 .ts 파일을 읽어 내부 코드를 가져와 Json으로 바꾸는 코드를 사용했다.

하지만 아래와 같이 eslint 쪽에서 에러가 발생했다.
error Unexpected `await` inside a loop no-await-in-loop

반복문 안에 await을 사용하지 말라면서 에러를 띄었다.

공식문서에선 for 안에 await을 사용하게 되면 성능 저하가 일어나기 때문에 사용하지 말라고 한다.

반복문을 await을 사용하여 병렬로 처리하게 된다면 배열을 예로 들때 for -> push -> for -> push -> for -> push 를 반복하게 되어 성능저하가 일어나기 때문이다.

그러면 공식문서에선 해결방안으로 Promise.all을 사용하면 된다.

위에서 사용한 코드를 Promise.all로 리펙토링 해보면

const commandPRC = async () => {
  const promises = [];
  for (let i = 0; i < commandFiles.length; i += 1) {
    const filePath = path.join(commandsPath, commandFiles[i]);
    const command = import(filePath);
    promises.push(command);
  }
  const results = await Promise.all(promises);
  return results.map((result) => result.default.data.toJSON());
};

commandPRC().then((commands) => {
	console.log(commands);
});

위와 같이 처리할 수 있게 된다.

async/await과 Pormise.all의 성능 차이는 https://code-masterjung.tistory.com/91 여기서 확인하면 된다.

참고 문헌 :
https://eslint.org/docs/rules/no-await-in-loop
https://dev.to/chandelieraxel/using-await-in-loop-cause-performance-issues-3amb
https://code-masterjung.tistory.com/91

profile
Journal

0개의 댓글