![article thumbnail image](https://blog.kakaocdn.net/dn/pJKcX/btrELVGqMZS/U7e3OBWSZGQwOjKfD1YVB1/img.png)
async 함수 : asyncFunction 객체를 반환하는 비동기 함수, 암시적으로 Promise를 반환한다
함수에 async를 붙인 경우에는 출력시 promise를 리턴하는 비동기처리 함수로 변화한다
// async function
async function helloAsync() {
return "hello Async";
}
helloAsync().then((res) => {
console.log(res);
});
async 를 붙이고 리턴하게되면 promise를 리턴하며, resolve 값으로 "hello Async"가 출력된다
//ms를 받아서 ms만큼 대기했다가 끝나기
function delay(ms) {
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
}
// async function
async function helloAsync() {
return delay(3000).then((res) => {
return "hello Async";
});
}
helloAsync().then((res) => {
console.log(res);
});
await : async 함수 안에서 사용되며 Promise를 기다릴 때 사용한다
// async function
async function helloAsync() {
//비동기 호출 앞에 붙으면 동기처리를 시키게됨
await delay(3000);
return "hello async";
}
helloAsync().then((res) => {
console.log(res);
});
위에 return delay를 await을 사용하여 동기적인 호출인 것 처럼 변환하였다
Promise가 fulfill되거나 reject 될 때까지 async function의 실행을 일시정지하고 Promise가 fulfill되면 일시정지한 부분부터 실행한다. 이때 await의 반환값은 fulfill값이다. 만약 Promise가 reject되면 await문은 reject된 값을 던진다.
await 이후에 실행되는 값이 promise가 아닐 경우 resolved promise로 변환한다
예제
//ms를 받아서 ms만큼 대기했다가 끝나기
function delay(ms) {
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
}
// async function
async function helloAsync() {
//비동기 호출 앞에 붙으면 동기처리를 시키게됨
await delay(3000);
return "hello async";
}
async function main() {
const res = await helloAsync();
console.log(res);
}
main();
참고 :
- https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Statements/async_function
- https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Operators/await
- 한입리액트
반응형
'개발 > Javascript' 카테고리의 다른 글
[node.js] node.js는 왜 써야할까? (0) | 2022.06.20 |
---|---|
[Javascript] API & fetch (0) | 2022.06.16 |
[Javascript] Promise (0) | 2022.06.14 |
[Javascript] 동기(synchronous) vs 비동기(asynchronous) (0) | 2022.06.13 |
[Javascript] Spread 연산자(Spread syntax); 전개구문 (0) | 2022.06.11 |