11
I’m running some tests with Promises and I found that there are two ways to get the result of a set of protocols:
using Promise.all()
:
async searchSegmentsInformations(segmentId) {
try {
const segment = await Segment.find(segmentId);
return segment;
} catch (error) {
throw new Error(error);
}
}
testePromises() {
const segmentsIds = [
{ id: 'bd84f021-30fb-4dad-b21a-6d673610db93' },
{ id: '25fcd038-58c2-44c2-aa9b-43529d591ed3' },
{ id: 'e1e9fd46-63ad-4ad9-af85-a16bd71a5b22' },
{ id: 'ca9f3a88-cb91-465a-87be-0c4bcfefa299' }
];
const teste = Promise.all(
segmentsIds.map((s) => this.searchSegmentsInformations(s.id))
)
.then((result) => {
return result
})
.catch((error) => {
console.log(error);
});
return teste;
}
with Promise.allSettled()
:
async searchSegmentsInformations(segmentId) {
try {
const segment = await Segment.find(segmentId);
return segment;
} catch (error) {
throw new Error(error);
}
}
testePromises() {
const segmentsIds = [
{ id: 'bd84f021-30fb-4dad-b21a-6d673610db93' },
{ id: '25fcd038-58c2-44c2-aa9b-43529d591ed3' },
{ id: 'e1e9fd46-63ad-4ad9-af85-a16bd71a5b22' },
{ id: 'ca9f3a88-cb91-465a-87be-0c4bcfefa299' }
];
const teste = Promise.allSettled(
segmentsIds.map((s) => this.searchSegmentsInformations(s.id))
)
.then((result) => {
const segmentsInformations = result.map((r) => r.value);
return segmentsInformations;
})
.catch((error) => {
console.log(error);
});
return teste;
}
What’s the difference between the two?
Both have the same compatibility?
When I should wear one or the other?