반복문에서 비동기 처리하기(for, for of, Promise.all)

Potato·2023년 5월 3일

TIL

목록 보기
6/10

for에서는 비동기 처리가되지 않는다.

React Native 프로젝트 진행 중 for 반복문을 통해 async/await 비동기 작업을 처리하던 중 분명히 작동해야하는 코드가 작동하지 않는 문제가 발생했다.

알고보니 JS의 for, forEach 에서는 비동기 작업이 끝나는 것을 대기하지 않는다는 것을 알았다.

for of

이를 해결하기 위해 for of를 사용해 코드 작성시 원하는 결과를 얻었다

for (const itemRef of storageRes.items) {
        const reference: any = ref(storage, itemRef.fullPath);
        const downloadUrl = await getDownloadURL(reference);
        const newImage = {
          uri: downloadUrl,
          path: reference._location.path,
          id: reference._location.path,
        };
        storagePhotos.push(newImage);
      }

Promise.all()

검색을 통해 답을 찾던 중 다른 적용가능한 방법도 알게되었고
Promise.all도 적용할 수 있겠다라는 생각이 들었다.

const downloadPromises = storageRes.items.map((itemRef) => {
  const reference = ref(storage, itemRef.fullPath);
  return getDownloadURL(reference).then((downloadUrl) => {
    const newImage = {
      uri: downloadUrl,
      path: reference._location.path,
      id: reference._location.path,
    };
    return newImage;
  });
});

const storagePhotos = await Promise.all(downloadPromises);

어떤게 더 유리할까?

위 두 코드는 동일한 동작을 수행한다.
하지만 일반적으로 Promise.all() 방법이 속도가 더 빠르다고하여 배열의 모든 요소에 동일한 비동기 작업을 수행할 때는 Promise.all() 을 사용하는 것이 더 효율적이라고 생각한다.

for of의 경우 배열의 일부 요소만 비동기 처리를 해야할 경우에 사용할 수 있을 것 같다.

0개의 댓글