<body>
<script>
const getJSON = function (url, errorMsg = "Something went wrong") {
return fetch(url).then((response) => {
if (!response.ok) throw new Error(`${errorMsg} (${response.status})`);
return response.json();
});
};
const get3APis = async function (c1, c2, c3) {
try {
const data1 = await getJSON(
`https://official-joke-api.appspot.com/random_joke`
);
const data2 = await getJSON(
`https://official-joke-api.appspot.com/random_joke`
);
const data3 = await getJSON(
`https://official-joke-api.appspot.com/random_joke`
);
console.log([data1, data2, data3]);
} catch (err) {
console.error(err);
}
};
get3APis();
</script>
</body>
get3Apis() 라는 함수를 통해서 api를 연달아 3번 호출하였다
위의 코드는 api를 한번 한번 호출 시 병렬적으로 처리되는게 아닌 순차적오 1, 2, 3을 하나 하나 받아오게된다
순차적으로 받오는게 아닌 병렬로 한번에 api를 호출하고 싶으면 Promise.all() 을 사용하면 된다
배열에 호출 중 하나라도 실패하면 값을 받지 못하니 이를 주의해서 사용하도록 하자
그러면 위의 코드를 병렬처리로 바꾸어보자
Promise.all()
const get3APis = async function (c1, c2, c3) {
try {
const data = await Promise.all([
getJSON(`https://official-joke-api.appspot.com/random_joke`),
getJSON(`https://official-joke-api.appspot.com/random_joke`),
getJSON(`https://official-joke-api.appspot.com/random_joke`),
]);
console.log(data)
} catch (err) {
console.error(err);
}
};
get3APis();
병렬처리를 필요로하는 api에 Promise.all 을 사용함으로서 데이터값을 한번에 받아올 수 있고 가독성도 높힐 수 있다
Promise.race()
race는 경주이다
뜻과 동일하게 배열로 담겨있는 api 리스트 중 가장 빠르게 받아온 데이터를 반환한다
(async function () {
const res = await Promise.race([
getJSON(`https://official-joke-api.appspot.com/random_joke`),
getJSON(`https://official-joke-api.appspot.com/random_joke`),
getJSON(`https://official-joke-api.appspot.com/random_joke`),
]);
console.log(res[0]);
})();
Promise.allSettled()
(async function () {
const res = await Promise.race([
getJSON(`https://restcountries.eu/rest/v2/name/italy`),
getJSON(`https://restcountries.eu/rest/v2/name/egypt`),
getJSON(`https://restcountries.eu/rest/v2/name/mexico`),
]);
console.log(res[0]);
})();
실패하면 데이터를 받아올 수 없는 all()과 달리 allSettled()은 성공,실패 여부와 상관없이 배열에 값을 담아준다
Promise.any()
any()는 race()와 비슷하지만 any()의 경우 배열안의 호출이 fullfilled(이행된) 것들에 한해서 보여진다
// Promise.any [ES2021]
Promise.any([
Promise.resolve('Success'),
Promise.reject('ERROR'),
Promise.resolve('Another success'),
])
'자바스크립트(JavaScript)' 카테고리의 다른 글
[리액트] 카카오 로그인 기능 구하기 (0) | 2022.12.17 |
---|---|
[자바스크립트] slice() (0) | 2022.12.07 |
[자바스크립트] 개방 폐쇄 원칙 SOLID : Open-Closed Principle (0) | 2022.12.04 |
[자바스크립트] 함수를 리턴하는 함수(Functions returning functions) (0) | 2022.11.13 |
[자바스크립트 ] 아규먼트 vs 파라미터(Argument vs Parameter) (0) | 2022.11.12 |