javascriptnode.jsnestjsrequest-promise

Promise.all not waiting to complete the requests


await Promise.all(
  endpoints.map((endpoint) =>
    this.httpService.get(endpoint).pipe(
      map((response) => {
        return response.data['result'];
      }),
    ),
  ),
).then(
  axios.spread((...allData) => {
    allData.forEach((res) =>
      res.subscribe((res) => {
        apiFeedBack.push(res);
        console.log(apiFeedBack);
      }),
    );
  }),
);

While debugging it is skipping promise.all execution and directly returns undefined as response. What am i missing here


Solution

  • First of all, when you are using await don't use then. This is how it be like:

    const promiseAll = async () => {
    try {
      const res = await Promise.all(promises);
      return res;
    } catch (e) {
     console.error(e);
    }
    }
    

    Now, we need to get the values from the promises using await, Also, it would be clean if you write it this way:

    const endpoints_Promises = endPoints.map(endPoint => {
     return new Promise((resolve, reject) => {
      this.httpService.get(endpoint).pipe(
        map((response) => {
          resolve(response.data['result']);
        })
       ) 
     })
    })
    try {
    const responses = await Promise.all(endpoints_Promises);
    responses.forEach(data =>  console.log(data));
    } catch (e) {
       console.error(`Error occured: ${e}`);
    }