ES6

10. async 와 await

으누아빠 2020. 7. 15. 16:34
반응형

async 와 await

  • 출처 https://www.youtube.com/watch?v=aoQSOZfz3vQ [드림코딩 by 엘리]
  • async, await은 promise를 좀더 간단하고 간편하게 동기적으로 실행
  • syntactic suger
  • 기존에 이미 존재하는 api를 확장하여 동일한 기능을 좀더 간편하게 사용할수 있도록 만들어진 api를 의미함

예: class

  • class는 전혀 새로운 것이 아닌 기존의 prototype을 base 로 한 살짝 덧붙여진 그럴싸한 syntactic suger
  • 즉 async, await는 promise를 base 로 한 syntactic suger

1. async

// 기존 promise 예제
function fetchUser() {
    return new Promise((resolve, reject) => {
        resolve('elle');
    });
}

const user = fetchUser();
user.then(console.log); //결과값 elle

//async 사용

async function fetchUser() {
    return 'elle';
}

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

// 결과값
// Promise {<resolved>: "elle"}
// elle

2. await

  • 관련 프로세스가 끝날때 까지 기다려...
  • async 가 붙어있는 함수안에서만 이용가능
  • 구문
    async function 함수명() { 
     await 비동기_처리_메서드_명();
    }
function delay(ms) {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve('done');
        }, ms);
    });
}

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

//일반
// function getApple(){
//     return delay(1000).then(()=>'🍎');
// }

//await을 이용
async function getApple() {
    // 3. getApple()를 비동기적으로 실행
    await delay(1000); // 4. delay(1000) 이 완료될때까지 기다려..
    return '🍎';
}

//일반
// function getBanana(){
//     return delay(1000).then(()=>'🍌');
// }

//await을 이용
async function getBanana() {
    await delay(1000);
    return '🍌';
}

async function pickFruits() {
    const apple = await getApple(); // 2. getApple()가 실행이 완료될때까지 기다려..
    const banana = await getBanana();

    // 5. 완료되면 apple 변수에 데이터 반환
    return `${apple} + ${banana}`;
}

pickFruits().then(console.log);

실행순서

  1. pickFruits()를 비동기적으로 실행
  2. getApple()가 실행이 완료될때까지 대기
  3. getApple()를 비동기적으로 실행
  4. delay(1000) 이 완료될때까지 대기
  5. 완료되면 apple 변수에 데이터 반환
  6. getBanana()가 실행이 완료될때까지 대기
  7. getBanana()를 비동기적으로 실행
  8. delay(1000) 이 완료될때까지 대기
  9. 완료되면 banana 변수에 데이터 반환
  10. pickFruits()가 완료되면 반환된값을 출력

3. Promise.all promise의 병렬처리

  • promise 배열을 전달하게 되면 모든 promise이 병렬적으로 다 받을때까지 모아줌
function pickAllFruits() {
    return Promise.all([getApple(), getBanana()]).then((fruits) => fruits.join(' + '));
}

pickAllFruits().then(console.log); //결과값 🍎 + 🍌

4. Promise.race

  • 병렬처리되는 promise 데이터 중 가장 먼저 처리가 완료된 데이터만 반환
function pickOnlyone() {
    return Promise.race([getApple(), getBanana()]);
}
pickOnlyone().then(console.log); //결과값 🍎

class UserStorage {
    loginUser(id, password) {
        return new Promise((resolve, reject) => {
            setTimeout(() => {
                if ((id === 'ellie' && password === 'dream') || (id === 'coder' && password === 'academy')) {
                    resolve(id);
                } else {
                    reject(new Error('not found'));
                }
            }, 2000);
        });
    }

    getRoles(user) {
        return new Promise((resolve, reject) => {
            setTimeout(() => {
                if (user === 'ellie' && password === 'dream') {
                    resolve({ name: 'ellie', role: 'admin' });
                } else {
                    reject(new Error('no access'));
                }
            }, 1000);
        });
    }
}

const userStorage = new UserStorage();
const id = prompt('enter your id');
const password = prompt('enter your password');

async function displayUser() {
    const user = await userStorage.loginUser(id, password);
    const getRole = await userStorage.getRoles(user);

    return getRole;
}

displayUser()
    .then((getRole) => {
        alert(`Hello ${getRole.name}, you have a ${getRole.role} role`);
    })
    .catch(console.log);

'ES6' 카테고리의 다른 글

array 와 arrow function 활용  (0) 2021.03.23
11. generators 생성기  (2) 2020.07.15
9. promise  (0) 2020.07.14
8. Set, Map, WeakSet, WeakMap  (0) 2020.07.09
7. New String & Number Methods  (0) 2020.07.08