0

I am trying to create generic function that can take functions as an array and execute it using promise.all , its throwing undefined exception.

main.ts

public async execute(@Request() request: express.Request): Promise < [any] | any > {
     const promises = [];
     promises.push(this.getAccountDetails, this.getCardDetails);
     return sendResponse(request, promises);
 }

 @Post('getAccountDetails')
 private async getAccountDetails(@Body() request: any): Promise < any > {
     // process retrieveData Call and get response 
 }

 @Post('getCardDetails')
 private async getCardDetails(@Body() request: any): Promise < any > {

     // process cardDetails Call and get response 
 }

commonFunction.ts

export function sendResponse(expressReq, promises) {
     const promiseCollector: any = [];
     promises.forEach(function(func: any) {
         if (expressReq.body.lineOfBusiness === "account") {
             promiseCollector.push(func(expressReq.body));
         }
         if (expressReq.body.lineOfBusiness === "credit") {
             promiseCollector.push(func(expressReq.body));
         }
     });

     return Promise.all(promiseCollector);

 }
hussain
  • 6,587
  • 18
  • 79
  • 152
  • You shouldn't call that array "promises" when actually it is an array of functions – Bergi Aug 14 '18 at 15:02
  • You are trying to pass a method as a callback. Assuming it uses `this`, you will need to bind it to the current instance - see the duplicate – Bergi Aug 14 '18 at 15:04
  • Are you sure this even does what you want if it worked? It's calling *both* functions if the `lineOfBusiness` matches either of the two values. If this is the expected behaviour, don't put the condition inside the loop. – Bergi Aug 14 '18 at 15:05
  • how to extract functions if i dont put in forloop, Can you please give me an example how to bind it to current instance duplicate question answers are little confusing – hussain Aug 14 '18 at 15:37
  • Extract from where? How would your code look if you didn't have `sendResponse` with the array parameter? – Bergi Aug 14 '18 at 15:41
  • Ok so i am passing both functions as a param to `sendResponses(req,this.getAcountDetails, this.getCardDetails)` and in commonFunction removed forloop just pushing functions to array inside condition like `if(condition === true) promiseCollector.push(func1(req.body)` and that gives response `Promises [ [AsyncFunction: getAccountDetails], [AsyncFunction: getCardDetails] ] [object Object]` – hussain Aug 14 '18 at 15:52
  • That doesn't look like you were calling the `func1`… – Bergi Aug 14 '18 at 18:40

0 Answers0