6

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 }) });
  }
1
  • Your code looks fine. I have tried running given snippet (with removed res.json(result);) and call to test function is successfully awaited and resolved. You problem must be somewhere else. Commented Apr 28, 2016 at 10:56

1 Answer 1

2

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));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.