210517_비동기

Bitnara Lee·2021년 5월 17일

비동기

어떤 경우에 중첩된 callback이 발생하는지 이해할 수 있다.
중첩된 callback의 단점, Promise 의 장점을 이해할 수 있다.
Promise 사용 패턴과 언어적인 특징들을 이해할 수 있다.
resolve, reject의 의미와, then, catch와의 관계를 이해할 수 있다.
Promise 에서 인자를 넘기는 방법에 대해 이해할 수 있다.
Promise의 세가지 상태를 이해할 수 있다.
Promise.all 의 사용법을 이해할 수 있다.
async/await keyword에 대해 이해하고, 작동 원리를 이해할 수 있다.
node.js의 fs 모듈의 사용법을 이해한다.

Asynchronous(동시에 일어나지 않는) / Synchronous(동시에 일어나는)
비동기 처리 : 이렇게 특정 로직의 실행이 끝날 때까지 기다려주지 않고 나머지 코드를 먼저 실행하는 것

callback - 동기적 or 비동기적으로 실행됨
함수실행연결x 함수자체 연결(ex)이벤트 핸들러)
Synchronous
Asynchronous

*callback 패턴

let request = 'pizza';
orderPizzaAsync(request, function(response){
  //response -> 주문한 피자 결과
  eat(response);
});
-----------------------------------------------------------
*이벤트 등록 패턴

let request = 'pizza';
orderPizzaAsync(request).onready = function(response){
  //response -> 주문한 피자 결과
  eat(response);
});

비동기의 주요 사례
DOM Element 이벤트 핸들러
-마우스,키보드 입력(click,keydown 등)
-페이지 로딩(DOMContentLoaded 등)
타이머
-타이머 API(setTimout 등)
-애니메이션 API(requestAnimationFrame)
서버에 자원 요청 및 응답
-fetch API
-AJAX (XHR)

new Promise 생성 유형


// 변수로 할당

const promise = new Promise((resolve,reject) => {
  console.log('doing something...');
  setTimeout(()=>{
     resolve('nara');     
     reject(new Error('no network'));  
  }, 2000);

}) 
--------------------------------------------------
// 함수가 리턴시킴

function fetchUser() {
    return new Promise((resolve, reject)=>{
        //do network request in 10 secs...
        resolve('nara');
    });
}
---------------------------------------------------
  
const getHen = () => 
  new Promise((resolve, reject) => {
    setTimeout(() => resolve('🐔'), 1000);
  });
--------------------------------------------------

class UserStorage {
    loginUser(id, password){ // 생성자함수가 리턴시킴
        return new Promise ((resolve, reject)=>{
            setTimeout(()=>{
              if(
                (id === 'nara' && password === 'artist') ||
                (id === 'enda' && password === 'dreamer')  
              ){
                 resolve(id); 
              }else {
                 reject(new Error('not found'));
              }      
            }, 2000)
        }) 
    } 
 --------------------------------------------------- 
// then으로 연결하는 과정에서 새 promise에 전달 가능
   
fetchNumber
  .then(num => num * 2)
  .then(num => num * 3)
  .then(num => {          
    return new Promise((resolve, reject)=>{        
      setTimeout(()=> resolve(num-1), 1000);
    })
  })
  .then(num => console.log(num));

then(): A method returns a Promise
If the function passed as handler to then returns a Promise, an equivalent Promise will be exposed to the subsequent(연속적으로 이어지는) then in the method chain(ex- 위 예시)

Error Handling

var p2 = new Promise(function(resolve, reject) {
  resolve(1);
});

Promise.reject()
  .then(() => 99, () => 42) // onRejected returns 42 which is wrapped in a resolving Promise
  .then(solution => console.log('Resolved with ' + solution)); // Resolved with 42
------------------------------------------------------------------------------
getHen()
 .then(hen => getEgg(hen)) // 값 받아서 인자로 넘겨줌 
 .catch(error =>{return '🥖'}) ->> 계란을 받아오는데 문제가 있어도 전체 promise 체인에 문제가 생기지 않도록 (cook에 빵전달)
 //.catch(console.log)  //   Error: error! 🐔=> 🥚 at promise.js:55 // undefined => 🍳  at promise.js:67
 .then(egg => cook(egg)) 
 //.catch(console.log) ->여기서 잡으면 에러메세지+ 밑 undefined 됨. 아무것도 넘겨주지 않아서?
 .then(meal => console.log(meal))
 .catch(console.log) // 에러가 밑으로 전달되서 잡혀짐 Error: error! 🐔=> 🥚 at promise.js:55
---------------------------------------------------------------------------------------
  .then(getEgg)  콜백함수를 전달할때 받아오는 value를 바로 다음함수에 전달시 생략 가능
  .then(cook) 
  .then(console.log);
 
profile
Creative Developer

0개의 댓글