Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Async/Await - Typescript and ExpressJs

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 }) });
  }
like image 348
Ali Salehi Avatar asked Apr 28 '16 07:04

Ali Salehi


1 Answers

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));
like image 171
smnbbrv Avatar answered Nov 15 '22 18:11

smnbbrv