2023-05-26[TIL]

jenna·2023년 6월 7일
1

TIL/WIL

목록 보기
30/60

Async Funtion

  • 비동기 함수의 결과값은 항상 Promise 객체로 resolve된다
  • 비동기 함수 안에서만 await연산자를 사용할 수 있다

await 연산자

: async 함수 내에서만 사용할 수 있으며, Promise의 비동기 처리가 완료될 때까지 함수의 실행을 일시 중단하고, Promise의 결과를 반환

  • 비동기 작업을 마치 동기 작업처럼 순차적으로 처리
  • Promise가 fulfill되거나 rejected될 때 까지 함수의 실행을 중단하고 기다릴 수 있다
  • promise가 아니여도 값을 resolved해 줌
async function getMyName(text) {return text}

await getMyName('A')
>A

getMyName('A').then(console.log);
>A

async 함수에서 promise를 return 한다면

const asyncTest = async() => {
  return Promise.resolve('값');
}

asyncTest().then(console.log)
>await asyncTest()
>'값'

await '값'
>'값'

return값이 promise일때는 그냥 promise를 return해줌

async 함수 값은 항상 promise로 감싸지지만 async return 값을 promise로 또 감싸는 이유
=> promise로 된 객체가 끝나는걸 기다리지 않아도 되면 그냥 return 가능

Promise all()

  • 순회 가능한 객체에 주어진 모든 프로미스가 이행한 후, 혹은 프로미스가 주어지지 않았을 때 이행하는 Promise를 반환
  • 주어진 프로미스 중 하나가 거부하는 경우, 첫 번째로 거절한 프로미스의 이유를 사용해 자신도 거부
const promise1 = Promise.resolve(3);
const promise2 = 42;
const promise3 = new Promise((resolve, reject) => {
  setTimeout(resolve, 100, 'foo');
});

Promise.all([promise1, promise2, promise3]).then((values) => {
  console.log(values);
});
// Expected output: Array [3, 42, "foo"]

위 코드에서 Promise.all([promise1, promise2, promise3])는 promise1과 promise2가 모두 이행될 때까지 기다리는 새로운 Promise를 반환

참고
https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Promise/all

profile
https://github.com/jennaaaaaaaaa

0개의 댓글