JavaScript

async & await

오류확인자 2023. 7. 4. 11:19

async 

// async

function hello() {
  return 'hello';
}

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

console.log(hello()); // hello
console.log(helloAsync()); // Promise {<pending>}
// pending promise를 출력하면 그대로 출력이 됨
// async를 붙이면 자동으로 비동기처리가 됨
// async

function hello() {
  return 'hello';
}

async function helloAsync() {
  return 'hello Async'; // Promise resolve로 반환함
}

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

 

await

// await

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

async function helloAsync() {
  await delay(3000); // await를 붙이게 되면 동기적으로 수행하게 됨.
  return "hello async";
}

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

// await 를 붙이게 되면 동기적으로 사용한다.
// 하지만 async 붙인 함수 안에서만 사용이 가능함

위 나와있듯이 await는 비동기적인것을 동기적으로 바꿔준다.

하지만 async 함수 내에서만 await를 사용할 수 있다.

 

// await

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

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

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

main();