[JS] async & await

짱효·2023년 10월 29일

JS

목록 보기
17/21

promise를 더욱 가독성있게!

async : 비동기를 다루는 것

  • async는 리턴하면 resolve값이랑 똑같다.
  • promise를 반환하도록 만드는 능력이 있따.
function hello(){
  return 'hello';
}
async function helloAsync(){
  return 'hello Async;
}

console.log(hello()) //hello
console.log(helloAsync()) //Primise{<pending>}
  • 프로미스를 반환하고있음

    -async를 붙여주면 비동기 처리되는 프로미스 객체가 나옴

then 붙여보기

  • async는 리턴하면 resolve값이랑 똑같다.
  • promise를 반환하도록 만드는 능력이 있따.
function hello(){
  return 'hello';
}
async function helloAsync(){
  return 'hello Async';
}

helloAsync().then((res)=>{
  console.log(res)
});


await

  • 비동기 함수가 동기적으로 된다.
  • await줄은 동기적으로 된다.
function delay(ms){
  return new Promise((resolve) => {
    setTimeout(resolve, ms)
	});
}
async function helloAsync(){
  return delay(3000).then(() => {
    return'hello Async';
});

helloAsync().then((res)=>{
  console.log(res)
});
  • await넣어서 수정
function delay(ms){
  return new Promise((resolve) => {
    setTimeout(resolve, ms)
	});
}
async function helloAsync(){
  await delay(3000);
  return'hello Async';
});

helloAsync().then((res)=>{
  console.log(res)
});
  • main함수 추가
function delay(ms){
  return new Promise((resolve) => {
    setTimeout(resolve, ms)
	});
}
async function helloAsync(){
  await delay(3000);
  return'hello Async';
});

function main(){
  const res = await helloAsync();
   console.log(res);
  });
}
main();

profile
✨🌏확장해 나가는 프론트엔드 개발자입니다✏️

0개의 댓글