콜백이 있는 비동기 자바스크립트 이해하기

Asynchronous javascript와의 첫 만남은 확실히 개념을 제대로 이해하기 어려웠습니다. 그래서 당면한 문제에 대한 조감도를 얻기 위해 각 개념 사이의 차이점을 배치하기 시작했습니다.

먼저 완전히 이해해야 하는 3가지 용어가 있다고 생각합니다.
  • 기능
  • 비동기
  • 콜백

  • 하나하나 밝혀보자.

  • Functions - Functions는 ** INVOKING** 이후 계산을 시작할 재사용 가능한 코드 세트입니다. (즉, 내가 전화할 때 이 코드를 수행합니다.)

  • 예를 들어

    function dugong(){
    //some code (reusable code)
    }
    
    dugong();//invoking || called , so start doing.
    



  • 비동기식 - Javascript는 코드를 한 줄씩 읽고 실행합니다. 이를 우리는 동기식(Synchronous)이라고 합니다. 정말 간단하지만 확장성이 뛰어난 웹사이트가 있는 코드를 실행하려는 경우에는 웹 사이트가 유휴 상태이거나 정지된 상태에서 특정 작업이 완료될 때까지 기다리십시오.

  • 따라서 이를 해결하기 위해 비동기식 자바스크립트가 작동합니다.

    기본적으로 비동기 자바스크립트는 환경의 주요 흐름을 방해하지 않고 무언가를 수행합니다. 비동기 자바스크립트의 만남은 이벤트입니다. 버튼을 '클릭'하면 그 안에 있는 코드가 실행되기 시작합니다. (즉, 내가 이것을 할 때(클릭) 이렇게 하십시오(코드))

    예를 들어

    btn.addEventListener('click' , ()=>{
    //some code
    }
    
    //this means after CLICKING then only it will execute.
    



  • 콜백 - 콜백은 다른 함수에 중첩된 함수입니다.

  • //higher order function
    function dugong(not_dugong){
    //some code
    not_dugong(); // callback function
    }
    
    


    이제 조건을 설정했으므로 예를 보여드리겠습니다. 이를 흥미롭게 만들기 위해 시나리오를 만들어 보겠습니다.

    시나리오 - 당신은 여자에게 데이트 신청을 하고, 그녀에게 꽃을 사주고, 영화를 보러 가고, 저녁을 사주고, 그녀에게 사랑한다고 고백했습니다. 그것에 대해 생각합니다. 그러나 당신은 단순한 사람이 아니며 그녀를 기다리지 않기 때문에 Anna와 Donna가 여전히 결정을 내릴 때 생각하는 동안 요청했습니다. (좋아요, 이 어리석은 이야기를 코딩해 봅시다..... 플레이어!)

    //here we have a function structure , lets take the first function example the " function lets_date(callback)" , the First Content of this function is that it will execute the "console.log('lets go on a date')" 
    
    function lets_date(callback){
        console.log('lets go on a date'); 
        callback(); // Moving on to the second line it finds that we INVOKED a function with a name of callback(); but there is no code content in the callback function , so it looks to the parameter of the main function (lets_date (parameter) ) and we can start constructing a batch of different code to execute there and so forth and if you want to call//invoke a set of other functions like in this case the "flowers() function" we include it in the callback function for it to be executed.
        } 
    
        function flowers(callback){
        console.log('buy flowers');
        callback();
        }
    
        function movies(callback){
        console.log('go to the movies');
        callback();
        }
    
        function dinner(callback){
        console.log('im broke but going to pay you for dinner');
        callback();
        }
    
        function confess(callback){
            console.log('You : i love you');
            console.log('Her : give me sometime to think about it')
            callback();
        }
    
        function not_a_simp(callback){
            console.log('i am not simp');
            callback();
        }
    
        function others(callback){
            console.log('ask anna out');
            callback();
        }
        function the_others(){
            console.log('ask dinnie out');
        }
    
        function love(){
            lets_date((callback)=>{ // you can just leave it an empty bracket also its fine , but im just trying to point out that this is the callback function and we state that in this callback function we have declared//invoked//called "flowers function" 
                flowers((callback)=>{
                    movies((callback)=>{
                        dinner((callback)=>{
                            confess((callback)=>{
                                not_a_simp((callback)=>{ // in this function we have a callback which have an async function which is SetTimeOut
                                    setTimeout((callback)=>{ // here would be asynchronous
                                        const yes = ()=>{ return console.log('One eternity later , Her : i love you too bro');  
                                }
    
                                if(yes){
                                    yes();
                                    console.log('You : i love you too back');
                                    console.log('You: lets get married')
                                }else {
                                    console.log('She rejected you , You : fcuk you');
                                }
    
                                    } , 15000)// here would be asynchronous
    
                                    others((callback)=>{
                                        the_others();
                                    })
                                })
                            })
                        })
                    })
                })
            })
        }
    
        love();
    


    그러나 이것은 이상적인 방법이 아닙니다. 중첩된 함수 위에 중첩된 함수가 있을 수 있기 때문에 우리는 이것을 콜백 지옥(callback hell)이라고 부릅니다. 여기에서 Promise 또는 async await를 사용하여 코드를 더 읽기 쉽게 만들 수 있습니다.

    이것이 통찰력이 있기를 바라며, 이 개념을 이해하는 것이 저에게 정말 도움이 되고 여러분에게도 도움이 되기를 바랍니다. 이에 대한 추가 설명이 필요하면 의견에 알려주십시오. 앞으로 Promise와 async에 대한 새로운 글을 올릴 예정입니다.

    좋은 웹페이지 즐겨찾기