[JS] 비동기

·2022년 10월 17일
0

JavaScript

목록 보기
20/25
post-thumbnail

22.10.17.월

사용자랑 인터렉션 하는데
내 할일하고 옆에서 통신한다~~
자살골이 나왔을 때 ??!!
한번 오류가 나면 뱉어버린다 다운되어버린다
그럼 안되니까 일단 보류하고 에러로 보류하고 나머지는 돌아가게 하려고~

비동기

a b c d 같이 청소를 하면 ~?

  • 동기 (순차적)
    a : 청소기 돌리고(10시)
    b : 빨래 하고 (11시)
    c : 설거지 하고 (12시)
    d : 요리한다 (1시)
  • 비동기 (순차적이지 않게끔)
    a : 청소기 돌리면서(10시)
    b : 빨래 하고 (10시)
    c : 설거지 하고 (10시)
    d : 요리한다 (10시)
  • 싱글 스레드 : 일할 수 있는 녀석이 한 명 ->JS (주문을 한 사람이 받는데 -코드를 실행시킬 수 있는 사람이 한 명인데- 주문을 받는 걸 멈춘다면 error!)
  • 멀티 스레드 : 일할 수 있는 녀석이 여러명~ -> 다른 언어 대부분이 지원

비동기 프로그래밍, 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)
  • pending(대기상태) - resolve(해결) - fulfilled(성공)
  • pending(대기상태) - reject(거부) - rejected(실패)

암기 1

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 상태였던 것! 비동기에 대해 좀 더 이해가 가는 부분이었다.

암기 2

문제
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);
    })

암기 3 (async)

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('!!')

암기 4 (await)

async function f() {

    let promise = new Promise((resolve, reject) => {
        setTimeout(() => resolve("완료!"), 1000)
    });

    let result = await promise; // 프라미스가 이행될 때까지 기다림 (*)
    alert(result); // "완료!"
}

f();

암기 5

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()
profile
주니어 프론트엔드 웹 개발자 🐛

0개의 댓글

관련 채용 정보