46 제너레이터 async/await

개발쟁이·2021년 6월 17일
0

제너레이터

: 함수의 실행을 중지 시킬수 있다. next메서드 호출시, yield까지 실행 하는방식으로 함수 호출자와 함수 상태를주고 받을 수 있다.

function* 함수명(){
  yield 
}

함수명.next() 

비동기 처리를 동기 처리처럼 구현 할수 있는 장점이 있어서, 리덕스 사가 할때 많이 쓰인다.

async/await

가독성있고 간단하게 비동기처리처럼 구현할수 있다. 비동기 처리 결과 후속 처리 없이 프로미스 사용 가능! (항상 async 는 암묵적으로 resolve하는 프로미스 반환 )
async는 생성자에서 사용 불가 생성자는, 인스턴스를 반환해야하는데 async는 프로미스를 반환하기 때문

async 실행하면 비동기 실행되고, settled 상태가 되면 await가 resolve 한 처리 결과를 반환

async를 사용할때 병렬적인 값인지, 서로 영향주는 값인지에따라 사용하는 키워드가 다름
병렬로 실행할때는 Promise.all을 써서 동시에 시작하는게 빠르고,

async function a(){
   const res = await Promise.all([
     new Promise (resolve => setTimeOut(()=> resolve(1), 3000)),
     new Promise (resolve => setTimeOut(()=> resolve(1), 4000)),
     new Promise (resolve => setTimeOut(()=> resolve(1), 1000))
     ]);
    console.log(res);
   }
  a();

각각의 영향을 받는다면 각각 await로 받아서 순서를 보장해야한다.

async function b(n){
 const t1 = await new Promise (resolve => setTimeOut(()=> resolve(1), 3000));
 const t2 = await new Promise (resolve => setTimeOut(()=> resolve(t1+1), 4000));
 const t3 = await new Promise (resolve => setTimeOut(()=> resolve(t2+2), 1000));
  ]);
    console.log([t1, t2, t3]);
   }
  b(1);

에러처리

async/awaittry catch 가능해서 try catch로 가능하고,

const fetch = require('node-fetch');
const a = async ()=>{
  try{
    const url ='www.123.12';
    const res = await fetch(url);
    const data = await res.json();
	}catch(err){
    console.log(err);
    }
};
a();

Promise를 리턴하는 만큼, then catch를 사용해도된다

const fetch = require('node-fetch');
const a = async ()=>{
  try{
    const url ='www.123.12';
    const res = await fetch(url);
    const data = await res.json();
};
a().then(console.log(data)).catch(console.error);
profile
개발 인생

0개의 댓글

관련 채용 정보