자바스크립트 async & await

OUO·2022년 3월 21일
0
post-thumbnail

🤸async

function hello() {
  return "hello";
}

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

console.log(hello());
console.log(helloAsync());

👉 async를 붙이면 자동으로 promise를 return 하는 비동기식처리 함수

function hello() {
  return "hello";
}

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

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

❗ async 붙이고 return만 해도 promise를 return 하면서 resolve를 "hello Async"로 수행한것과 똑같은 결과를 얻음

🤸await

function delay(ms) {
  return new Promise((resolve) => {
    setTimeout(resolve, ms); // settimeout 함수의 콜백함수 안에 resolve 호출 외에는 아무것도 없으면 callback함수 자체를 resolve로 전달
  });
}

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

helloAsync().then((res) => {
  console.log(res);
});
function delay(ms) {
  return new Promise((resolve) => {
    setTimeout(resolve, ms); // settimeout 함수의 콜백함수 안에 resolve 호출 외에는 아무것도 없으면 callback함수 자체를 resolve로 전달
  });
}

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

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

👉 await 함수를 비동기 함수의 호출 앞에 붙이면 비동기 함수가 마치 동기적인 함수처럼 작동

❗ async 붙어있는곳에만 사용이 가능

❗ await가 붙은 함수의 호출은 뒤에있는 함수가 끝나기 전까지 아래 있는 코드 수행 x = await줄에는 다 동기적으로 수행

profile
develoops!er

0개의 댓글