fetch('https://api.github.com/users/Yena-Yun')
.then((res) => {
return res.json(); // 응답을 json 형식으로 반환
}).then((res) => {
console.log(res); // 성공 시 데이터 출력
}).catch((err) => {
console.log(err); // 실패 시 오류 출력
});
function walk(amount) {
return new Promise((resolve, reject) => {
// amount가 500 미만이면 reject 문구 출력 후 종료
if (amount < 500) {
reject("the value is too small");
}
// amount 시간 뒤에 resolve의 문구 출력
setTimeout(() => resolve(`you walked for ${amount}ms`), amount);
});
}
walk(1000).then((res) => {
console.log(res);
return walk(700); // 700초 후 resolve 반환 (you walked for 700ms)
}).then((res) => {
console.log(res);
return walk(400); // reject 반환 후 종료 (uncaught exception: the value is too small)
// catch를 쓰지 않았기 때문에 앞에 'uncaught exception:'이 붙는다
}).then((res) => {
console.log(res);
return walk(100); // reject 이후의 then은 출력되지 않는다
});
async/await로 바꾸려면 다음과 같은 단계가 필요하다.
function walk(amount) {
return new Promise((resolve, reject) => {
if (amount < 500) {
reject("the value is too small");
}
setTimeout(() => resolve(`you walked for ${amount}ms`), amount);
});
}
// 비동기 함수 선언
async function go() {
const res = await walk(1000); // async가 있어야 await 사용 가능
console.log(res);
const res2 = await walk(700); // resolve 출력
console.log(res2);
const res3 = await walk(400); // reject 출력 후 종료
console.log(res3);
const res4 = await walk(100);
console.log(res4);
}
// 비동기 함수 호출
go();
기본 프로미스 코드와 마찬가지로 try/catch 문을 사용한다.
async function asyncFunc() {
try {
const response = await fetch(URL);
} catch(err) {
console.log(err);
}
}
asyncFunc(); // TypeError: failed to fetch