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
CodePudding user response:
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);
}),
);
}),
)
CodePudding user response:
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}`);
}
CodePudding user response:
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?