์ƒ์„ธ ์ปจํ…์ธ 

๋ณธ๋ฌธ ์ œ๋ชฉ

[์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ] async await

์นดํ…Œ๊ณ ๋ฆฌ ์—†์Œ

by esoesmio 2023. 5. 18. 02:08

๋ณธ๋ฌธ

function getMult10Promise (number) {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve(number * 10);
        }, 1000);
    });
}

async function doAsyncWorks () {
    const result1 = await getMult10Promise(1);
    console.log(result1);

    const result2 = await getMult10Promise(2);
    console.log(result2);

    const result3 = await getMult10Promise(3);
    console.log(result3);
}

doAsyncWorks();
console.log('๐Ÿ’ก ์ด ๋ฌธ๊ตฌ๊ฐ€ ๋จผ์ € ์ถœ๋ ฅ๋จ');

 

 

// ๋นŒ๋ฆฐ ๊ธˆ์•ก์œผ๋กœ ์•ฝ์†์„ ํ•˜๋Š” ํ•จ์ˆ˜
function moneyLend (borrow) {
    return new Promise((resolve, reject) => {
        console.log(`์ฑ„๋ฌด ${borrow}๋งŒ์›`);

        setTimeout(() => {
            if (Math.random() < 0.1) {
                reject('์ฑ„๋ฌด์ž ํŒŒ์‚ฐ');
            }

            resolve(borrow * 1.1);
        }, 1000);
    });
}

async function lend5times () {
    try {
        const lend1 = await moneyLend(20);
        const lend2 = await moneyLend(lend1);
        const lend3 = await moneyLend(lend2);
        const lend4 = await moneyLend(lend3);
        const lend5 = await moneyLend(lend4);

        console.log(`๐Ÿ’ฐ ๋ฐ˜๋‚ฉ ${lend5}๋งŒ์›`);
    } catch (msg) {
        console.error(msg);
    } finally{
        console.log('- - ๋Œ€๊ธˆ์—… ์ข…๋ฃŒ - -');
    }
}

lend5times();

 

const DEADLINE = 1400;

function getRelayPromise (name, start, failMsg) {
    console.log(`๐Ÿ‘Ÿ ${name} ์ถœ๋ฐœ`);

    // ๐Ÿ’ก ๋žœ๋ค ์‹œ๊ฐ„๋งŒํผ ๋‹ฌ๋ฆฌ๊ณ  ๊ฒฐ๊ณผ๋ฅผ ๋ฐ˜ํ™˜ํ•˜๊ฒ ๋‹ค๋Š” ์•ฝ์†์„ ๋งŒ๋“ค์–ด ๋ฐ˜ํ™˜
    return new Promise((resolve, reject) => {
        const time = 1000 + Math.random() * 500;

        setTimeout(() => {
            if (time < DEADLINE) {
                console.log(`๐Ÿšฉ ${name} ๋„์ฐฉ - ${(start + time)/1000}์ดˆ`);
                resolve(start + time);

            } else {
                console.log(failMsg);
                reject((start + time) / 1000);
            }
        }, time);
    })
}

async function relay5 () {
    try {
        const time1
            = await getRelayPromise('์ฒ ์ˆ˜', 0, '์ฒ ์ˆ˜๋ถ€ํ„ฐ ๊ด‘ํƒˆ์ž…๋‹ˆ๋‹ค. ใ… ใ… ');

        const time2
            = await getRelayPromise('์˜ํฌ', time1, '์˜ํฌ๊ฐ€ ์™„์ฃผํ•˜์ง€ ๋ชปํ–ˆ๋„ค์š”.');

        const time3
            = await getRelayPromise('๋Œ์ค€', time2, '๋Œ์ค€์ด ๋ถ„๋ฐœํ•ด๋ผ.');

        const time4
            = await getRelayPromise('์ •์•„', time3, '์ •์•„์—๊ฒŒ ๋ฌด๋ฆฌ์˜€๋‚˜๋ณด๋„ค์š”.');

        const time5
            = await getRelayPromise('๊ธธ๋ˆ', time4, '์•„์•„, ์•„๊น์Šต๋‹ˆ๋‹ค...');

    } catch (msg) {
        console.log(`๐Ÿ˜ข ์™„์ฃผ ์‹คํŒจ - ${msg}์ดˆ`);
    } finally {
        console.log('- - ๊ฒฝ๊ธฐ ์ข…๋ฃŒ - -');
    }
}

relay5();

 

 

๋Œ“๊ธ€ ์˜์—ญ