0
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

qwerty
  • 9
  • 1
  • 7

3 Answers3

0

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}`);
}
Apoorva Chikara
  • 8,277
  • 3
  • 20
  • 35
0

folks as you may know that @nestjs/axios in NestJS returns observable rather then promise however this is not the case of axios.

So in case you need to make observable asynchronous you will need to convert it to promise, although it's not a recommended way and .toPromise() is deprecated in the latest version of @nestjs/axios.

Promise.all(
  return endpoints.map((endpoint) =>
    this.httpService.get(endpoint).toPromise(),
  ),
).then((responses)=> {
   // here you get the resolved promises responses array
})

Check this out to learn more about Promise.all fulfillment.

Check this out for more information if you should be using observable async/await Is it a good practice using Observable with async/await?

-1

You need to return the array of promises received from the map function as below:

await Promise.all(
  return 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);
      }),
    );
  }),
)
Siddharth Seth
  • 643
  • 5
  • 18
  • 1
    This will cause a `SyntaxError` as the `Promise.all` function expects an expression and not a `return` keyword. The problem lies in that there are no promises returned *inside* the `map` function. – Emiel Zuurbier Mar 09 '22 at 06:34