ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 1. callback function - Synchronous & Asynchronous
    JavaScript 2021. 6. 10. 14:07

     

    JavaScript is synchronous.

    Execute the code block by orger after hoisting.

    hoisting: The declaration of a var or a function is lifted.

     

     

    Let's see an example

    console.log('1');   
    // -> sync
    
    setTimeout(() => console.log('2'), 1000);   
    // -> async
    
    console.log('3');   
    // -> sync
    
    
    // Synchronous callback
    function printImmediately(print){
        print();
    }
    printImmediately(() => console.log('hello'));   
    // -> sync
    
    
    // Asynchronous callback
     function printWithDelay(print, timeout){
         setTimeout(print, timeout);
     }
     printWithDelay(()=> console.log('async callback'), 2000); 
     // -> async

     

    I put a mixture of Sync functions and Async functions.

    And the following results can be seen.

    Sync functions are executed in batches first.

    And Async functions are excuted on time set.

     

     

    The method of using callbacks is a common approach to asynchronous programming.

    Let's make it a simple login using a callback.

     // Callback Hell example
     
     // 1.
     class UserStorage {
         loginUser(id, password, onSuccess, onError){
             setTimeout(() => {
                if(
                    (id === 'lexie' && password === 'sehong') ||
                    (id === 'sehong' && password === 'lexie')
                ) {
                    onSuccess(id);
                } else {
                    onError(new Error('not found'));
                }
             },2000);
         }
         // 2. 
         getRoles(user, onSuccess, onError){
            setTimeout(() => {
                if(
                    (user === 'lexie')
                ) {
                    onSuccess({ name: 'lexie', role: 'admin'});
                } else {
                    onError(new Error('not access'));
                }
             }, 1000);
         }
     }
    
     // 3.
     const userStorage = new UserStorage();
     
     // 4.
     const id = prompt('enter your id');
     const password = prompt('enter your password');
     
     // 5.
     userStorage.loginUser(
         id,
         password,
         user => {
             userStorage.getRoles(
                                    user, 
                                    userWithRole => {
                                        alert(`Hello ${userWithRole.name}, you have a ${userWithRole.role} role`)
                                    },
                                  error => console.log(error));
             },
         error => console.log(error)
     );
    
    

     

    1. Create a function that receives an ID and password and excecutes the function according to the match.

    2. If the ID is lexie, create a function that tells you the permission.

    3. Create a new UserStorage

    4. Receive an ID and password

    5. Pass id and password, onSuccess function and error function to execute login function

     

     

    So, every new action is inside a callback. It too complecated and readability is bad..

    That’s fine for few actions, but not good for many, so we’ll see other variants soon.

     

     

    There's more detail  > https://javascript.info/callbacks

    kor ver > https://ko.javascript.info/callbacks

     

     

     

     

     

     

     

    'JavaScript' 카테고리의 다른 글

    reduce()  (0) 2021.06.11
    map()  (0) 2021.06.10
    forEach()  (0) 2021.06.10
    3. async & await  (0) 2021.06.10
    2. Promise  (0) 2021.06.10

    댓글

Designed by Tistory.