async 또한 promise처럼 비동기를 다루는 기능이자 promise를 더 쉽게 이용할 수 있도록 도와주는 친구
function hello() {
return "hello";
}
async function helloAsync(){
return "hello Async";
}
console.log(hello()); //hello
console.log(helloAsync());//Promise{<pending>}
함수에 async를 붙이게 되면 이 함수는 자동적으로 promise를 리턴하는 비동기처리 함수가 된다.
helloAsync()가 promise를 반환하고 있다는 뜻은 호출할ㅇ 필요없이 then을 쓸 수 있다는 얘기
function hello() {
return "hello";
}
async function helloAsync(){
return "hello Async";
}
helloAsync().then((res)=>{
console.log(res);
});
//hello Async
async라는 키워드를 붙여준 함수의 리턴값은 비동기작업 객체 promise의 resolve의 결과값이 됨
async는 함수에 옵션을 붙이듯 붙여서 그 함수가 promise를 반환하도록 만드는 능력이 있음
//delay함수는 밀리세컨드를 파라미터로 받아 밀리세컨드만큼 대기했다가 끝나는 비동기 함수
function delay(ms){
return new Promise((resolve)=>{
setTimeout(resolve, ms);
});
}
//setTimeout()의 콜백함수안에 resolve()를 호출하는 것 말고 없으면 콜백함수자체를 resolve()로 전달해도 상관없음
async function helloAsync(){
return delay(3000).then(()=>{
return "hello Async";
});
}
helloAsync().then((res)=>{
console.log(res);
});
//hello Async
이 코드를 await을 이용해서 바꾸면
//delay함수는 밀리세컨드를 파라미터로 받아 밀리세컨드만큼 대기했다가 끝나는 비동기 함수
function delay(ms){
return new Promise((resolve)=>{
setTimeout(resolve, ms);
});
}
//setTimeout()의 콜백함수안에 resolve()를 호출하는 것 말고 없으면 콜백함수자체를 resolve()로 전달해도 상관없음
async function helloAsync(){
await delay(3000);
return "hello Async";
}
helloAsync().then((res)=>{
console.log(res);
});
//hello Async
await이라는 키워드를 비동기함수의 호출 앞에 붙이게 되면 비동기함수가 마치 동기적인 함수처럼 작동하게 됨
await키워드가 붙은 함수의 호출은 뒤에 있는 함수가 끝나기 전까지 아래에 있는 코드를 수행하지 않음
-> await 줄은 모두 동기적으로 수행됨
await키워드는 async키워드가 붙은 함수 내에서만 사용 가능
//delay함수는 밀리세컨드를 파라미터로 받아 밀리세컨드만큼 대기했다가 끝나는 비동기 함수
function delay(ms){
return new Promise((resolve)=>{
setTimeout(resolve, ms);
});
}
//setTimeout()의 콜백함수안에 resolve()를 호출하는 것 말고 없으면 콜백함수자체를 resolve()로 전달해도 상관없음
async function helloAsync(){
await delay(3000);
return "hello Async";
}
async function main(){
const res = await helloAsync();
console.log(res);
}
main();
//hello Async