Promise.all
Promise.all()
메서드는 요소 전체가 Promise인 배열(엄밀히 따지면 이터러블 객체이지만, 대개는 배열임)을 받고 새로운 Promise를 반환한다. Promise.all
에 전달되는 Promise 중 하나라도 거부되면, Promise.all
이 반환하는 Promise는 에러와 함께 바로 거부된다.
categories/1
과 categories/3
API 주소에 각각 요청을 보내고 한 번에 데이터를 받아오기 위해 다음과 같이 Promise.all()
메서드를 사용했다.
const [data, setData] = useState(null);
const categoryNum = [1, 3];
useEffect(() => {
Promise.all(
categoryNum.map(num =>
fetch(`http://...(생략).../categories/${num}`)
)
)
.then(res => Promise.all(res.map(res => res.json())))
.then(json => {
setData(json.map(data => data.message));
});
}, []);
정말 감사합니다 이 글 덕분에 해결 됐어요.... ㅠㅠ