I am experiencing with typescript's async/await in express. I have the following code snippet which doesn't product any outcome, it just waits as if the promise is never finished. Any ideas how to make it work.
  ..
  router.get('/test', this.test);
  ..
  private async test(req: Request, res: Response) {
    const result = await this.test2();
    res.json(result);
  }
  private async test2() {
    return await this.test3();
  }
  private test3() {
    return new Promise((resolve) => { resolve({ "working": true }) });
  }
update:
If I change the first line with the line below, it works. Any ideas why ?
router.get('/test', (req,res)=>this.test(req,res));
update2 (fixed) - based on @smnbbrv answer below
 private test = async(req: Request, res: Response)=> {
    const result = await this.test2();
    res.json(result);
  }
  private test2 = async ()=> {
    return await this.test3();
  }
  private test3 = async()=> {
    return new Promise((resolve) => { resolve({ "working": true }) });
  }
                Looks like your 'this' is lost after you pass it like that
router.get('/test', this.test);
If you simply preserve the this value by
router.get('/test', this.test.bind(this));
this should work exactly in the way you mentioned in update
router.get('/test', (req,res)=>this.test(req,res));
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With