본문 바로가기

Javascript

[Javascript] async / await 비동기

반응형

1) async 앞에 있으면 promise와 같다

function myFunc() {
    return 'func';
}

async function myAsync() {
    return 'async';
}

console.log(myFunc());
console.log(myAsync());

결과 :

 

2) async 안의 함수에 return이 myAsync 호출하는 then의 result값에 찍힌다

async function myAsync() {
    return 'async';
}

myAsync().then((result)=> {
    console.log(result);
});

결과 :

async

 

3)

function delayP(sec) {
    return new Promise((resolve, reject)=> {
        setTimeout(()=> {
            resolve(new Date().toISOString());
        }, sec * 1000);
    });
}

async function myAsync() {
    delayP(3).then(time=>{
        console.log(time);
    })
    return 'async';
}

myAsync().then((result)=> {
    console.log(result);
});

결과

async
(3초후)
2022-01-20T04:14:13.120Z

 

4)

function delayP(sec) {
    return new Promise((resolve, reject)=> {
        setTimeout(()=> {
            resolve(new Date().toISOString());
        }, sec * 1000);
    });
}

async function myAsync() {
    await delayP(3);
    return 'async';
}

myAsync().then((result)=> {
    console.log(result);
});
(3초후)
async

 

5)

function delayP(sec) {
    return new Promise((resolve, reject)=> {
        setTimeout(()=> {
            resolve(new Date().toISOString());
        }, sec * 1000);
    });
}

async function myAsync() {
    const time = await delayP(3);
    console.log(time)
    return 'async';
}

myAsync().then((result)=> {
    console.log(result);
});
(3초후)
2022-01-20T05:34:24.487Z
async

 

6)

function delayP(sec) {
    return new Promise((resolve, reject)=> {
        setTimeout(()=> {
            resolve(new Date().toISOString());
        }, sec * 1000);
    });
}

async function myAsync() {
    const result = await delayP(3).then((time) => {
        return 'x';
    });
    console.log(result)
    return 'async';
}

myAsync().then((result)=> {
    console.log(result);
});
(3초후)
x
async

 

7) 일반함수앞에 await 하여도 return 값 찍힌다

(await 붙히는것 안붙히는것 같다)

function normalFun() {
    return 'wow';
}

async function myAsync() {
    const result = await normalFun();
    console.log(result);
    
    return 'async';
}
wow
async

 

출처 : https://www.youtube.com/watch?v=JzXjB6L99N4

반응형