> For the complete documentation index, see [llms.txt](https://triplexlab.gitbook.io/vanilla-js/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://triplexlab.gitbook.io/vanilla-js/03./02.-async-await.md).

# 03. async/await

## async/await

async/await 문법은 ES8에 해당하는 문법으로서, Promise 를 더욱 쉽게 사용 할 수 있게 해줍니다.

기본적인 사용법을 알아봅시다.

```javascript
const sleep = (ms) => {
    return new Promise(resolve => setTimeout(resolve, ms));
}

async function process() {
    console.log('안녕하세요!');
    await sleep(1000);
    console.log('반갑습니다.!');
}

process();
```

```javascript
// 결과)
안녕하세요!
반갑습니다.!
```

async/await 문법을 사용할 때에는, 함수를 선언 할 때 함수의 앞부분에 `async` 키워드를 붙여주세요. 그리고 Promise 의 앞부분에 `await` 을 넣어주면 해당 프로미스가 끝날때까지 기다렸다가 다음 작업을 수행 할 수 있습니다.

위 코드에서는 `sleep` 이라는 함수를 만들어서 파라미터로 넣어준 시간 만큼 기다리는 Promise 를 만들고, 이를 `process` 함수에서 사용해주었습니다.

함수에서 `async` 를 사용하면, 해당 함수는 결과값으로 Promise 를 반환하게 됩니다. 따라서 다음과 같이 코드를 작성 할 수 있습니다.

```javascript
const sleep = (ms) => {
    return new Promise(resolve => setTimeout(resolve, ms));
}

async function process() {
    console.log('안녕하세요!');
    await sleep(1000);
    console.log('반갑습니다.!');
}

process().then(() => {
    console.log('작업 끝났어요!')
});
```

```javascript
// 결과)
안녕하세요!
반갑습니다.!
작업 끝났어요!
```

`async` 함수에서 에러를 발생 시킬때에는 `throw` 를 사용하고, 에러를 잡아낼 때에는 try/catch 문을 사용합니다.

```javascript
function sleep(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

async function errorMake() {
    await sleep(3000);
    const error = new Error();
    throw error;
};

async function process() {
  try {
    await errorMake();
  } catch (e) {
    console.log('then error : ', e)   // 여기서 e는 위에 throw error;를 가리키게 됩니다.!!
  }
}

process();
```

```javascript
// 결과)
then error : error
```

### **EX1)**&#x20;

`new Promise` 로 정의 하는 코드&#x20;

```javascript
function a(value) {
    return new Promise((resolve, reject) => {
        setTimeout(function() { // 여기서 setTimeout 한것은 서버와의 통신에서 시간을 걸린다는 가정해서 이미를 setTimeout함수를 사용한것입니다.
            resolve(value)
        },1000)
    })
}

function b(value) {
    return new Promise((resolve, reject) => {
        setTimeout(function() {  // 여기서 setTimeout 한것은 서버와의 통신에서 시간을 걸린다는 가정해서 이미를 setTimeout함수를 사용한것입니다.
            resolve(value)
        },1000)
    })
}

function c(value) {
    return new Promise((resolve, reject) => {
        setTimeout(function() {  // 여기서 setTimeout 한것은 서버와의 통신에서 시간을 걸린다는 가정해서 이미를 setTimeout함수를 사용한것입니다.
            resolve(value)
        },1000)
    })
}

function d(value) {
    return new Promise((resolve, reject) => {
        setTimeout(function() {  // 여기서 setTimeout 한것은 서버와의 통신에서 시간을 걸린다는 가정해서 이미를 setTimeout함수를 사용한것입니다.
            resolve(value)
        },1000)
    })
}

function test(value) {
    return new Promise((resolve, reject) => {
        if(false) { // 정상적으로 서버와 통신못하면 (에러 나면) 실행됩니다.
            reject('Error') //reject('원하는 메세지 작성')
        }
        setTimeout(() => {  // 여기서 setTimeout 한것은 서버와의 통신에서 시간을 걸린다는 가정해서 이미를 setTimeout함수를 사용한것입니다.
            resolve(value) 
        }, 1000);
    })
}
```

**then catch 실행하는 코드**

```javascript
// then catch 실행하는 코드

test('A').then((res) => {console.log(res)})
.then(() => b("B").then((res) => {console.log(res)}))
.then(() => c("C").then((res) => {console.log(res)}))
.then(() => d("D").then((res) => {console.log(res)}))
.catch((error) => {
    console.log(error)
    alert(error)
})
.finally(() => {
    console.log('done!!')
    alert('done!!')
})
```

**ES8버전 async await 실행하는 코드**

```javascript

// ES8버전 async await 실행하는 코드

async function asyncFunc() {
    try {
        const a0 = await test('A!')
        console.log(a0)
        const a1 = await a('A')
        console.log(a1)
        const b1 = await b('B')
        console.log(b1)
        const c1 = await c('C')
        console.log(c1)
        const d1 = await d('D')
        console.log(d1)
    } catch (error) {
        alert(error)
        console.log(error)
    } finally {
        console.log('done!!')
    }
}

asyncFunc()
```

{% file src="/files/-M7Sa304QaCV7LNKAHfz" %}
async.js 예시
{% endfile %}
