[TIL 2021.10.14] js async await (완강)

Kyu·2021년 10월 14일
0

TIL

목록 보기
277/322

Today I Learned
async, await


// 1. async 개선전 
function fetchUser() {
    // doing network request taking 10 secs..
    // return 'kyu';
    
    // instead of those code above
    return new Promise((resolve, reject) => {
        // doing network request taking 10 secs..
        resolve('kyu');
    })
    
}

const user = fetchUser(); // it'll take 10 secs
user.then(console.log);
console.log(user); // and return this 
// the problem is nothing will appear on screen while doing that

// -----------------------위에 기존 Promise를 async로 개선-----------------------///
// 1. async 개선후
async function fetchUser() {
        // doing network request taking 10 secs..
    return 'kyu';
}

const user2 = fetchUser(); // it'll take 10 secs
user2.then(console.log);
// easy money

// -------------------------------------------------------------------------

// 2. await 
// await은 async가 붙은 함수에만 사용가능
function delay(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}

async function getApple() {
    await delay(2000);
    return 'apple';
}

async function getBanana() {
    await delay(1000);
    return 'banana';
}

// function pickFruits() {
//     return getApple().then(apple => {
//         return getBanana().then(banana => `${apple} + ${banana}`);
//     });
// }

// async function pickFruits() {
//     const apple = await getApple();
//     const banana = await getBanana();
//     return `${apple} + ${banana}`;
// }

// pickFruits().then(console.log);

// 3. useful Promise APIs
function pickAllFruits() {
    return Promise.all([getApple(), getBanana()])
        .then(fruits => fruits.join(' + '));
}
pickAllFruits().then(console.log);

function pickOnlyOne() {
    return Promise.race([getApple(), getBanana()]);
}

pickOnlyOne().then(console.log);

done youtube js tutorial by dream coding with ellie 1~13

profile
TIL 남기는 공간입니다

0개의 댓글