헉!!/javascript
[Javascript] async & await
권태성
2024. 7. 21. 00:00
Playwright를 사용하기 위해 짧게나마 notion에 정리내용을 블로그에 옮김
async
- 함수를 비동기 실행하도록 해줌 return promise
await
- 비동기 함수 앞에 붙여 호출할 경우 비동기 함수를 동기 형태로 사용할 수 있음
- await 은 뒤에 있는 함수의 결과를 대기함
//일반 함수
function hello() {
return "hello";
}
//async를 붙이면 promise를 반환하는 비동기 객체가 됨
async function helloAsync() {
return "hello async";
}
console.log(hello());
console.log(helloAsync()); //return promise
helloAsync().then((res) => {
console.log(res); //then을 이용해 실제 async 함수의 결과 출력
});
function delay(ms) {
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
}
async function helloAsync() {
return delay(3000).then(() => {
return "hello async";
});
}
helloAsync().then((res) => {
console.log(res);
});
위 코드에 await을 적용할 경우 아래 처럼 사용할 수 있음
function delay(ms) {
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
}
async function helloAsync() {
await delay(3000);
return "hello async";
}
helloAsync().then((res) => {
console.log(res);
});
function delay(ms) {
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
}
async function helloAsync() {
await delay(3000);
return "hello async";
}
async function main() {
const res = await helloAsync();
console.log(res);
}
main();
728x90