0

I am using Promise.all to merge responses but if one promise fails it throws the error i have one promise returning successful call but one fails how can i fix this issue by resolving both promises ?

buildHeader function will take both responses whatever returns from both calls if its an error that should come back as well so i can have part of details

main.ts

private async execute(@Request() request: ExpressRequest): Promise < any > {
    let _combineData: any =[];
    try {
        const _dataSpecialty = this.specialtyHandler.specialtyRequestHandler(request);
        const combinedResponses = await Promise.all([
            _dataSpecialty,
            this.caremarkHandler.caremarkRequestHanlder(request)
        ]);

        _combineData = this.buildHeader(combinedResponses, request.body);
    } catch(err) {
        return err;
    }
    return _combineData;
}


private buildHeader(combinedResponse: any[],
    request: ICombinedAccountBalanceRequest): any {
    return {
        getAccountBalanceResponse: {
            header: makeVordelSuccessHeader(request),
            details: combinedResponse
        }
    };
}
JJWesterkamp
  • 7,559
  • 1
  • 22
  • 28
hussain
  • 6,587
  • 18
  • 79
  • 152
  • Have a look at [`Promise.race`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/race). – JJWesterkamp Oct 18 '18 at 21:18
  • I don't think `race` helps here @JeffreyWesterkamp. If the first promise rejects, that's what race will return. – Mark Oct 18 '18 at 21:20
  • Wouldn't race, combined with catch calls chained to the contained promises do the job? – JJWesterkamp Oct 18 '18 at 21:22
  • Oh nevermind. I see the problem now. – JJWesterkamp Oct 18 '18 at 21:23
  • So you want to create `_combineData` once both responses come back, and if at least one is successful? (Only throw the error if neither are successful, is that it?) – CertainPerformance Oct 18 '18 at 21:25
  • @CertainPerformance i updated my question so i am building final response for client after both promises returns if one of them fail still want error from that promises to be pushed to details – hussain Oct 18 '18 at 21:27
  • If you want to `race()` only resolved promises and not rejected promises, just `.catch(() => new Promise(() => {}))` to each of the promises that are passed to `race()` so that rejections result in a promise that never settles. – Patrick Roberts Oct 18 '18 at 21:35
  • I understand Promise.all will return response or nothing but just trying to get an error from promise that is failing so i can add that to final response as well for client so they can see the error. catch will return the error how i would know which promise failed ? – hussain Oct 18 '18 at 21:39

0 Answers0