# JavaScript async 와 await

### async.await​​

**promise를 좀 더 간편하고 동기적으로 실행되는것처럼 보이게 만들어주는것**

### async

```javascript
// async & await 
// clear style of using promise :)
// promise를 좀 더 깔끔하게 사용하게 만들어줌 

// 1.async 
async function fetchUser() {
   //do network reqeust in 10 secs....
    return 'ellie';
}
// async 라는 키워드를 사용하면 promise랑 똑같은 기능을 수행함

const user = fetchUser();
user.then(console.log);
console.log(user);
```

### await

```javascript
// 2. await
function delay(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}

async function getOrange () {
    await delay(2000);
    return '🍊';
}
// await async가 붙어 있는 함수 안에서만 사용이 가능하다. 
// 체이닝을 안하고 동기적은코드를 적는것 처럼 단순화가 됨 

async function getBanana() {
    await delay(1000);
    return '🍌';
}
// promise도 마찬가지로 너무 많이 중첩되서 사용하다보면 콜백지옥을 만들어냄 
// function pickFruits() {
//    return getOrange()
//        .then(orange => {
//            return getBanana().then(banana => `${orange} + ${banana}`);
//        });
// }

async function pickFruits() {
        const orangePromise = getOrange(); //프로미스를 만드는 순간 코드블럭 실행
        const bananaPromise = getBanana(); //프로미스를 만드는 순간 코드블럭 실행
        const orange = await orangePromise; //동기
        const banana = await bananaPromise; //동기
        return `${orange} + ${banana}`
}
// 순차적으로 처리하면 비효율적임 오렌지 1초기다리고 바나나 1초기다리고 생성하기 떄문에 2초가 소요됨 
// 그래서 따로 오랜지,바나나 Promise를 따로 만들어서 동시에 실행되게 함 (병렬적으로 기능을 수행)
// 하지만 코드가 지저분해지는 단점이 있음 
```

### useful promise APIs

```javascript
// useful promise APIs 
// 위의 async function pickFruits() {} 코드를 병렬적으로 정리해줌
function pickAllFruits() {
    return Promise.all([getOrange(), getBanana()])
        .then(fruits => fruits.join(' + ')); // Orange , Banana 받아지면 join
}
pickAllFruits().then(console.log) // 성공하면 consle.log 출력
// promise.all 을 사용해 간편하게 처리 

function pickOnlyOne() {
    return Promise.race([getOrange(), getBanana]); 
    //어떤과일이던 첫번째 과일을 받고 싶다. -> 가장먼저 리턴하는 값만 전달됨 (.race)
}

pickOnlyOne().then(console.log); // 🍌

```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://leeboa.gitbook.io/study/_/javascript-async-await.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
