22.10.17.월
사용자랑 인터렉션 하는데
내 할일하고 옆에서 통신한다~~
자살골이 나왔을 때 ??!!
한번 오류가 나면 뱉어버린다 다운되어버린다
그럼 안되니까 일단 보류하고 에러로 보류하고 나머지는 돌아가게 하려고~
a b c d 같이 청소를 하면 ~?
비동기 프로그래밍, JS 실행구조를 왜 알아야할까?
one()
페이지 로드하고
two()
서버에서 이미지와 상세 데이터를 받아오고(예 - http://test.api.weniv.co.kr/mall) - 시간이 걸린다 - pending
three()
읽어온 데이터를 뿌려준다 - resolve
four()
페이지에 정적 데이터 로드
new Promise((resolve, reject) => {
//code
})
.then(result => result)
.then(result => result)
.catch(err => err)
.finally(result => result)
let p = new Promise(function(resolve, reject){
// 비동기적으로 실행될 code 작성
resolve('hello world')
}).then(메시지 => {
alert(메시지)
return 메시지.split(' ')[0]
}).then(메시지 => {
alert(메시지)
throw Error('Error 발생! 경고경고!')
return 메시지[0]
}).then(메시지 => {!
alert(메시지)
return 메시지
}).catch(메시지 => {
console.log(메시지)
alert('catch 실행!!')
})
console.log(p)
실행 후 콘솔창을 보면
왜 Promise {<pending>}
으로 되어있을까?
까보면 [[PromiseState]] : "fulfilled"
로 되어있긴 한데
실행은 다 했으니 fullfilled가 되어야하는 거 아닐까?
따로 찍어보면!
console.log(p) 결과로 fullfilled가 나온 걸 확인할 수 있다
같이 찍으면 console.log(p)가 다른 코드들이 실행되는 동안 실행되어서 pending 상태였던 것! 비동기에 대해 좀 더 이해가 가는 부분이었다.
문제
1. 추가 then을 사용하여 7개의 항목 productName만 출력해보세요.(console.log)
2. 추가 then을 사용하여 7개의 항목 중 price가 10000원 이상 되는 product를 출력하는 코드를 작성해주세요.(console.log)
3. 추가 then을 사용하여 7개의 항목의 productName과 price를 각각 h2와 p태그로 생성하여(DOM) 화면에 출력해주세요.
4. error 처리를 해주세요.
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 => {
console.log(
productData
.map(item => item.price)
.filter(item => item >= 10000)
)
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);
})
async는 Promise의 문법적 설탕이다.
async function f() {
return 100;
}
f().then(alert); // 100
////////////////////
async function f() {
return 'hello world';
}
console.log('!')
f()
.then(메시지 =>{
alert(메시지)
return 메시지.split(' ')[0]
})
.then(메시지 =>{
alert(메시지)
return 메시지[0]
});
console.log('!!')
async function f() {
let promise = new Promise((resolve, reject) => {
setTimeout(() => resolve("완료!"), 1000)
});
let result = await promise; // 프라미스가 이행될 때까지 기다림 (*)
alert(result); // "완료!"
}
f();
async function getData(){
const response = await fetch(`http://test.api.weniv.co.kr/mall`);
const productData = await(response.json());
console.log(productData);
console.log(productData.map((item) => item.productName));
console.log(productData.map((item) => item.price).filter((item) => item > 10000));
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);
}
getData()