[JS] 동기 / 비동기 / 프로미스

2022. 6. 15. 12:39·Stack/JavaScript

자바스크립트 비동기 처리
동기적처리(Synchronous)
비동기적처리(Asynchronous)

1. 콜백함수

2. Promise

자바스크립트에서 제공하는 비동기를 간편하게 처리할 수 있도록 도와주는 오브젝트입니다.

기능을 수행하고 나서 정상적으로 기능이 수행되면 성공의 메세지와 처리된 결과값을 전달

수행하다가 예상치 못한 결과가 생기면 에러를 전달해줍니다.

 

프로미스 상태

state: Promise가 수행중이면 pending

          수행이 종료되면 fullfilled

          수행중 오류가 발생 rejected

 

프로듀서와 컨슈머

프로듀서: Promise 제공

컨슈머: Promise 사용

 

 


 

synchronous.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>
        // function work() {
        //     const start = Date.now();
        //     for(let i=0; i<1000000000; i++) {

        //     }
        //     const end = Date.now();
        //     console.log(end-start+'ms');
        // }
        function work(callback) {
            setTimeout(()=>{
                const start = Date.now();
                for(let i=0; i<1000000000; i++) {

                }
                const end = Date.now();
                console.log(end-start+'ms');
                callback();
            }, 0)
        }
        console.log('work 호출하기');
        work(()=>{
            console.log('작업이 끝났어요');
        });
        console.log('다음 작업');
    </script>
</body>
</html>

 

 

 

callback.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>
        // function loadScript(src) {
        //     // script 태그를 만들고 페이지에 script 태그를 추가합니다.
        //     // 태그가 페이지에 추가되면 src에 있는 스크립트를 로딩하고 실행합니다.
        //     let script = document.createElement('script');
        //     script.src = src;
        //     document.head.append(script);
        // }
        // loadScript("myScript.js");
        // printHi();
        function loadScript(src, callback){
            let script = document.createElement('script');
            script.src = src;
            script.onload = () => callback();
            document.head.append(script);
        }
        loadScript("myScript.js", function() {
            printHi();
        })
    </script>
</body>
</html>

 

myScript.js

function printHi() {
    console.log("안녕 ~~ !!");
}

 

 

 

callback2.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>
        console.log('1');
        setTimeout(()=>{
            console.log('2');
        }, 2000)
        // for(let i=0; i<1000000000; i++) {
        // }
        // console.log('2');
        // console.log('3');
        
        function printConsole() {
            console.log("자바스크립트 콜백 !")
        }
        
        // Synchronous 콜백 실습
        function printImmediately(print) {
            print();
        }
        printImmediately(printConsole);

        // asynchronous 콜백 실습
        function printWithDelay(print, timeout) {
            setTimeout(print, timeout);
        } 
        printWithDelay(printConsole, 2000);
    </script>
</body>
</html>

 

 

 

promise.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>
        // 1. 프로미스 프로듀서
        const promise = new Promise((resolve, reject)=>{
            console.log('수행중......');
            setTimeout(()=>{
                resolve("성공한 결과");   // resolve 실행 뜸
                // reject("에러발생");    // reject 실행 뜸
                // reject(new Error('찾을 수 없어'));
            },2000)
        });

        console.log(promise);
        // 2. 프로미스 컨슈머 then, catch, finally
        // promise.then(value=>{
        //     console.log(value);
        // })
        // promise.then(
        //     // function(a){
        //     //     console.log('resolve 실행')
        //     //     console.log(a)
        //     // },   // 결과를 다룹니다.
        //     (a)=>console.log(a),
        //     // function(e){
        //     //     console.log('reject 실행')
        //     //     console.log(e)
        //     // }   // 에러를 다룹니다.
        //     e=> {
        //         console.log('reject 실행')
        //         console.log(e)
        //     }
        // )

        // 성공한 결과는 then이 처리 실패하면 catch가 처리
        promise.then(value=>{
            console.log(value);
        })
        .catch(error => {
            console.log(error);
        }).finally(()=>{
            console.log("끝났어요");
        })
    </script>
</body>
</html>

'Stack > JavaScript' 카테고리의 다른 글

[JS] canvas  (0) 2022.06.16
[JS/JSON] ShoppingList  (0) 2022.06.15
[JS/JSON] JSON(; JavaScript Object Notaion)  (0) 2022.06.14
[JS] 클래스 복습  (0) 2022.06.14
[JS] 배열 / 객체 / set 복습  (0) 2022.06.13
'Stack/JavaScript' 카테고리의 다른 글
  • [JS] canvas
  • [JS/JSON] ShoppingList
  • [JS/JSON] JSON(; JavaScript Object Notaion)
  • [JS] 클래스 복습
7ingout
7ingout
  • 7ingout
    Hello, 7ingout world!
    7ingout
  • 전체
    오늘
    어제
    • 분류 전체보기 (205)
      • Project (5)
      • Stack (173)
        • React (40)
        • JavaScript (50)
        • TypeScript (14)
        • HTML (11)
        • CSS (31)
        • Spring (9)
        • PHP (15)
        • SQL (3)
        • Python (0)
      • ETC (9)
      • Design (13)
        • Illustrator (6)
        • Photoshop (7)
      • Articloid (4)
        • 7ingout (4)
  • 공지사항

    • ☻
  • 인기 글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.0
7ingout
[JS] 동기 / 비동기 / 프로미스
상단으로

티스토리툴바