자바스크립트 - map 함수에서 비동기 함수 사용하기 async, Promise.all

반응형

map 함수에서 비동기 사용하기

async function asynFunction(id) {
  const res = await fetch('https://dummyjson.com/products/${id}');
  const data = await res.json();
  console.log(data);
  return data
}

const array = [1, 2, 3, 4, 5];
const userList = array.map(async (id) => await asyncFunction());

console.log(userList);

 

위와 같이 map 함수에서 비동기 함수를 호출하게 되면 아래와 같이 데이터의 결과 값들이 아니라

Promise 객체가 반환 됩니다.

 

await 의 경우에는 promise 객체는 기다리지만, promise 배열은 기다려주지를 않습니다.

 

Promise.all()

const userList = await Promise.all(array.map(async (id) => await asynFunction(id)))

 

위와 같이 Promise.all 함수를 이용해서 사용해야 합니다.

Promise.all 함수의 경우에 배열내에 실행을 하고 싶은 모든 비동기 함수를 실행하게 됩니다.

Promise 배열로 이루어진 비동기 함수를 모두 실행시키기 때문에

userList에 정상적으로 데이터를 넣을 수 있게 됩니다.

 

 

728x90
반응형