async/await룰

송승찬·2020년 10월 16일
0

TIL

목록 보기
44/52
async/await has 4 simple rules:

1.A function handling an asynchronous task must be marked using the async keyword.
2.await promise operator pauses the function execution until promise is either resolved successfully or rejected.
3.If promise resolves successfully, the await operator returns the resolved value: 
const resolvedValue = await promise. 
Otherwise, you can catch a rejected promise inside try/catch.
4.An async function always returns a promise, which gives the ability to nest async functions.
In simple words, when JavaScript encounters await Promise in an async function, 
it pauses the function execution until the promise is resolved or rejected. 
The promise’s resolved value becomes the result of await promise evaluation.
async function 함수명() {
  await 비동기_처리_메서드_명();
}
- 함수의 내부 로직 중 promise반환하는 **비동기 처리 코드 앞에 await**를 붙여야.

- 일반적으로 await의 대상이 되는 **비동기 처리 코드는 Axios,fetch 등 프로미스를 반환하는 API 호출 함수**

await
- 반환된 Promise의 resolve상태까지 대기한다.
- await의 값은 Promise의 resolve에 전달된 값이 반환된다.
- 즉, 비동기 함수의 Promise가 resolve상태일때,Promise의 resolve()로부터 결과값을 추출
- async 키워드가 붙어있는 함수를 호출하면 명시적으로 Promise 객체를 생성하여 리턴하지 않아도 Promise 객체가 리턴
const fetchItem = () =>{
  return new Promise((resolve,reject)=>{
    resolve(['Seoul','Lite'])
  })
}


async function logItems() {
  var resultItems = await fetchItem();
  console.log(resultItems); // [1,2,3]
}
logItems();

참고

profile
superfly

0개의 댓글