자바스크립트의 비동기 요청으로 인해 병렬로 처리할 때, 너무 많은 요청이 들어오면 429상태코드와 함께 에러가 출력이 된다.
async/await를 통해 비동기로 다른 호출을 만들기 전에 이전 호출의 응답을 기다리는 차단 구조를 만들면 시간이 더 오래 걸리지만 문제가 해결되지 않는다.
이럴 경우 세마포어를 이용하면 병렬처리의 양을 제한하여 너무 많은 병렬처리로 인한 오류를 차단할 수 있다.
import {RateLimit} from "async-sema";
위처럼 세마포어(RateLimit)를 임포트하여 최대 병렬 요청을 5개로 제한하면 오류없이 처리할 수 있다.
import fetch from "node-fetch";
import {RateLimit} from "async-sema";// configure a limit of maximum 5 requests / second
const limit = RateLimit(5);const data = [{ id: 1 }, { id: 2 }, [+1000 more objects]];
const fetchFromApi = (id) => {
const url = `https://example.com/api/my-resource/${id}`;// use the configured throttle here
const response = fetch(url)
.then((x) => x.json())
.catch((error) => console.log(error));
return response;
};
for (const i of data) {
// checks if limit is reached
await limit()
fetchFromApi(i.id).then((result) => console.log(result));
}