// 동기 - 순차적
// 호준 : 로봇 청소기 돌리고(10시)
// 호준 : 빨래하고(11시)
// 호준 : 설거지하고(12시)
// 호준 : 요리한다(1시)
// 비동기 - 비순차적
// 호준 : 로봇 청소기 돌리면서(10시)
// 호준 : 빨래도 돌리고(10시)
// 호준 : 설거지하고(10시)
// 호준 : 요리할려고 물도 끓이고(10시)
const one = '1';
const two = '2';
const three = '3';
console.log(one);
setTimeout(() => {
console.log(two);
}, 1000);
console.log(three);
let p = new Promise(function(resolve, reject) {
// 실행코드
});
// resolve(value) — 작업이 성공적으로 마무리되면 호출, 결과는 value에 담김
// reject(error) — 작업이 실패시 호출, error는 error에 담김
// 쉬운 예제
let p = new Promise(function(resolve, reject) {
resolve('hello world');
}).then(메시지 => {
alert(메시지);
return 메시지.split(' ')[0]
}).then(메시지 => {
alert(메시지);
return 메시지[0]
}).then(메시지 => {
alert(메시지);
});
let p = new Promise(function(resolve, reject) {
// resolve('hello world');
reject('hello world');
}).then(메시지 => {
alert(메시지);
return 메시지.split(' ')[0]
}).then(메시지 => {
alert(메시지);
return 메시지[0]
}).then(메시지 => {
alert(메시지);
}).catch(메시지 => {
alert('catch 실행!! :' + 메시지);
});
let p = new Promise(function(resolve, reject) {
// resolve('hello world');
reject('hello world');
}).then(메시지 => {
alert(메시지);
throw Error("에러 발생!")
return 메시지.split(' ')[0]
}).then(메시지 => {
alert(메시지);
return 메시지[0]
}).then(메시지 => {
alert(메시지);
}).catch(메시지 => {
alert('catch 실행!! :' + 메시지);
});
let p = new Promise(function(resolve, reject) {
// resolve('hello world');
// reject('hello world');
resolve('hello world');
}).then(메시지 => {
alert(메시지);
throw Error("에러 발생!")
return 메시지.split(' ')[0]
}).then(메시지 => {
alert(메시지);
return 메시지[0]
}).then(메시지 => {
alert(메시지);
}).catch(메시지 => {
alert('catch 실행!! :' + 메시지);
});
let p = new Promise(function(resolve, reject) {
setTimeout(() => resolve("끝남!"), 3000);
});
console.log('hello world');
console.log(p);
//3초 후 다시 실행
console.log(p);
fetch는 자바스크립트에서 제공하는 비동기 통신 API입니다. 이를 사용하면 서버에 네트워크 요청을 보내고 새로운 정보를 받아올 수 있습니다. Promise를 기반으로 구현되어 있어, .then()
이나 .catch()
를 통해 응답을 처리할 수 있습니다.
예제 코드에서는 fetch()
를 사용하여 http://test.api.weniv.co.kr/mall GET 요청을 보내고, 응답 데이터를 받아와 다양한 방식으로 처리하는 과정을 보여줍니다. 응답 데이터는 .json()
메서드를 통해 자바스크립트 객체로 변환됩니다.
이후 .then()
을 연쇄적으로 사용하여 데이터를 가공하는 과정을 거칩니다. 상품명 출력, 가격 필터링, DOM 요소 생성 및 화면 출력 등의 작업을 수행합니다. .catch()
를 통해 에러 처리도 이루어집니다.
fetch는 네트워크 요청을 간편하게 처리할 수 있는 강력한 도구이며, 현대 자바스크립트에서 널리 사용되고 있습니다.
fetch('<http://test.api.weniv.co.kr/mall>')
.then(productData=>productData.json())
.then(productData=>productData)
.then(productData => {
console.log(productData.map(item => item.productName));
return productData;
})
.then(productData => {
const main = document.createElement("main");
productData.forEach(item => {
const ProductCard = document.createElement("article");
const productName = document.createElement("h2");
const productPrice = document.createElement("p");
productName.textContent = `상품명 : ${item.productName}`;
productPrice.textContent = `가격 : ${item.price}`;
ProductCard.appendChild(productName);
ProductCard.appendChild(productPrice);
main.appendChild(ProductCard);
})
document.body.appendChild(main);
})
.catch(error => {
alert('에러!')
// error page로 리다이렉트
console.log(error);
})