
async function myFunc() {} 내부에서 fetch API를 사용하여 서버에 요청을 보내면, promise를 resolve하는 방법은 다음과 같습니다.
1. fetch API의 then() 메서드 사용: fetch API의 then() 메서드를 사용하여 promise를 resolve할 수 있습니다. 예를 들어, 다음과 같이 사용할 수 있습니다.
#hostingforum.kr
javascript
async function myFunc() {
const response = await fetch('https://example.com/api/data');
const data = await response.json();
return data;
}
2. async/await 문법 사용: async/await 문법을 사용하여 promise를 resolve할 수 있습니다. await 키워드를 사용하여 promise를 기다리게 되는데, 이 때 promise가 resolve되기까지의 시간이 오래 걸린다면, 서버와의 통신이 지연될 수 있습니다. 그러나 async/await 문법은 promise를 기다리기 때문에 지연을 피할 수 있습니다.
#hostingforum.kr
javascript
async function myFunc() {
try {
const response = await fetch('https://example.com/api/data');
const data = await response.json();
return data;
} catch (error) {
console.error(error);
}
}
3. Promise.all() 메서드 사용: Promise.all() 메서드를 사용하여 여러 promise를 동시에 resolve할 수 있습니다. 예를 들어, 다음과 같이 사용할 수 있습니다.
#hostingforum.kr
javascript
async function myFunc() {
const promises = [
fetch('https://example.com/api/data1'),
fetch('https://example.com/api/data2'),
fetch('https://example.com/api/data3'),
];
const responses = await Promise.all(promises);
const data = await Promise.all(responses.map(response => response.json()));
return data;
}
이러한 방법 중 하나를 사용하여 promise를 resolve할 수 있습니다.
2025-07-24 13:57