0
//service class
    async importExcel(userId, file){
      const business = await this.getBusinessByUserId(Types.ObjectId(userId));
      let errorData = [];
      readXlsxFile(file, {schema}).then(async ({rows, errors}) => {
        if(errors.length === 0){
          await this.excelUploadQueue.add({
            rows,
            business
          })
        }
        errors.forEach((error) => {
          const errors = {
            column: error.column,
            value: error.value,
            reason: error.reason,
          }
          errorData.push(errors)
        });
        console.log(errorData); can access the errorData here
      }) 
      console.log(errorData); cannot access it here, i want to access it here so that i
      return errorData; // can return it here to my controller
   
     }

//controller

@UseGuards(JwtAuthGuard)
  @UseInterceptors(FileInterceptor('file'
  , {
    storage: diskStorage({
      destination: './csv',
      filename: (req, file, cb) => {
        const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9)
        cb(null, file.fieldname + '-' + uniqueSuffix + "-" + file.originalname)
      }
    })
  }
  ))
  @Post('/import-excel/employee')
  @ApiOperation({summary: 'upload exployee data via excel'})
  async uploadExcel(
    @UploadedFile() file: Express.Multer.File,
    @Request() req
    ){
      const { id: userId } = req.user;
      return await this.businessService.importExcel(userId, file.path);
  }

How can i go abt it,been on it for some hours....When i apply a settimeout like the below code setTimeout(() => { console.log(errorData) // i could access it but its not returning to my controller }, 100);

Abhay
  • 27
  • 7
  • Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Ivar Jul 31 '22 at 14:41
  • 1
    "async forEach" are two words [that don't go very well together](https://stackoverflow.com/questions/37576685/using-async-await-with-a-foreach-loop). In general I'd avoid `.forEach()` where possible. But that being said, your specific `.forEach()` doesn't await anything, so there is no reason for it to be `async` in the first place. – Ivar Jul 31 '22 at 14:42
  • i was actually doing sth on it that was why it was there...will remove it now..thanks for bringing my awareness to it – Abhay Jul 31 '22 at 14:44
  • have removed the async from the forEach and its still the same thing – Abhay Jul 31 '22 at 14:45
  • My second comment was just a side note. Your main problem is explained in the post linked in my first comment. – Ivar Jul 31 '22 at 14:46

1 Answers1

0

Don't mix async/await syntax with .then() calls. Just write

async importExcel(userId, file) {
  const business = await this.getBusinessByUserId(Types.ObjectId(userId));
  const {rows, errors} = await readXlsxFile(file, {schema});
//                       ^^^^^
  if (errors.length === 0) {
    await this.excelUploadQueue.add({
      rows,
      business
    })
  }
  const errorData = errors.map(error => ({
    column: error.column,
    value: error.value,
    reason: error.reason,
  }));
  console.log(errorData); // can access the errorData here
  return errorData; // and can return it here to my controller
}

The problem is not even related to the forEach loop, you simply were trying to access errorData outside of the then callback. And btw, never use an async callback to forEach - easily fixed in your case since the callback didn't actually do anything asynchronous (though I still wonder why you need this at all - you're creating new objects with exactly the same properties as the errors, maybe just return errors directly?).

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • thanks alot....i also thought of it but was so disturbed to not think very well....it has worked ..thanks very much – Abhay Jul 31 '22 at 14:49
  • there are still some error data that i dont need to be displayed that was why i used the foreach to take out what i needed..thanks...your solution solve my issue – Abhay Jul 31 '22 at 14:55