Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to return a promise in a nestjs interceptor?

I have created a Class implementing NestInterceptor().

As it returns an Observable(), when I have a promise in it, it does not wait the promise to return the data. How should I do that?
Here is my code:

 export class PointsInterceptor implements NestInterceptor {
      intercept(context: ExecutionContext, next: CallHandler): Observable<any> {

var monaddress = context.switchToHttp().getRequest().body
var retour

//Using Promise
geocoder.geocode(monaddress)
.then(function(res) {
    console.log('res: '+ res);
    retour = res[0].latitude;
  
  })
  .catch(function(err) {
    console.log(err);
    retour = err
  })  ;
  return next.handle().pipe(map(retour => ({ retour })))
}
}

return is executed before the geocoder promise.
I tried to put the return on success and error. A warning is rised:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

A function whose declared type is neither 'undefined', 'void', nor 'any' must return a value.ts(2355)

PS: As this is a nestJS interceptor, I have to keep the class returning the Observable().

>Solution :

Why don’t you use async/await syntax like below

async intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
  var monaddress = context.switchToHttp().getRequest().body
  var retour

  cost res = await geocoder.geocode(monaddress)
  console.log('res: '+ res);
  retour = res[0].latitude;

  return next.handle().pipe(map(retour => ({ retour })));
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading