[JS] async & await - 직관적인 비 동기 처리 코드 작성하기

n-u·2022년 6월 15일
0

TIL

목록 보기
9/24
post-thumbnail

🔅 async(에이싱크)

async 키워드는 함수에 붙여 Promise를 반환하는 기능을 가진다.

비동기를 다루는 기능이자, promise를 더 쉽게 쓸수 있다.
async를 함수 앞에 붙여주면, 자동적으로 함수는 Promise를 리턴하게 되는 함수가 되어 비동기 처리 함수가 된다.
그렇다면, async는 then을 사용할 수도 있다.

function hello() {
  return "hello";
}

async function helloAsync() {
  return "Hello Async";
}

console.log(hello()); //hello
console.log(helloAsync()); //Promise {<pending>}

async 키워드를 가지고 함수는 then을 이용할 수 있다.

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

//Hello Async

async키워드를 붙인 함수의 리턴값은 비동기 작업 객체의 Promise에 resolve값이 되어 then의 콜백함수의 인자로 들어올 수 있다.

따라서 Hello Async는 helloAsync()함수의 리턴값이자 비동기 처리의 resolve값이다.

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(어웨이즈)

await키워드가 붙은 함수는 그 함수가 실행이 끝나기 전까지 그 아래의 코드를 실행시키지 않는다.
즉, 동기적으로 사용하는 것처럼 작동하며,
await는 async 키워드가 붙은 함수 안에서만 사용이 가능하다.

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()함수에 async와 await를 이용

async와 await를 이용해 Promise를 반환하는 함수를 동기적으로 호출되도록 할 수 있다.

function delay(ms) {
  return new Promise((resolve) => {
    setTimeout(resolve, ms);
  });
}

async function helloAsync() {
  await delay(3000);
  return "hello Async";
}

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

main();

//비동기 코드 Promise를 반환하는 코드를 동기적인 함수로 호출하는 함수로 만들 수 있다.
profile
기록하며 발전하는 삶

0개의 댓글