async & await

oasis·2023년 3월 11일
1

JavaScript

목록 보기
4/6
post-thumbnail

💙 개요

timer(1000,function(){
  console.log('작업');
  timer(1000,function(){
  	console.log('작업');
  });
});

비동기 작업시
타이머 작업 후 또 타이머 작업을 해야한다면..
콜백안에 반복해서 콜백이 들어가는 .. 콜백 지옥 발생
--> 이 때문에 promise가 등장!

promise를 적용한 코드

timer(1000)
  .then(function(){
    console.log('작업')
  	return timer(1000);
  })
  .then(function(){
    console.log('작업')
  	return timer(1000);
  })

여기서 만족하지 않고 발전한 것이.. async&awiat

async & await

동기적 코드처럼 작성하는 문법적 단순화

  • 비동기적인 코드 앞에 await붙이기
  • await이 붙은 프로미스를 리턴하는 함수는 반드시 다른 어떤 함수 안에 들어가있어야 하고, 그 함수는 async라는 키워드가 붙어있어야 함
async funtion run(){
  await timer(1000)
  console.log('작업')
  await timer(1000)
  console.log('작업')
  }
run();


💙 예제

console.log('start');
timer(1000).then(function(time){
  console.log('time:'+time);
  return timer(time+1000);
}).then(function(time){
  console.log('time:'+time);
  return timer(time+1000);
}).then(function(time){
  console.log('time:'+time);
  console.log('end') // 함수안에 적지 않으면 timer보다 먼저 end가 나옴
});

출력

start
time:1000
time:2000
time:3000
end

async & await 활용

async function run() {
  console.log('start');
  var time = await timer(1000); //timer가 비동기적이라는 것을 명확하게 함
  console.log('time:'+time);
  time = await timer(time+1000);
  console.log('time:'+time);
  time = await timer(time+1000);
  console.log('time:'+time);
  console.log('end')
}

async function run2(){
  console.log('parent start');
  var time = await run();
  console.log('parent end');
}

run();
  • await를 쓰면 timer(1000)의 리턴값을 time으로 받는데, 이는 .then(function(time){})의 time과 같은 것임
  • async가 붙은 run()이라는 함수는 비동기적인 함수: promise를 리턴함
    - 앞에 await를 또 붙일수 있다는 의미
  • async는 평범한 함수를 프로미스를 리턴하는 비동기적으로 만들어주는 키워드이고, 그렇가 때문에 그 안에서 await를 사용할 수 있는 것

0개의 댓글