简体   繁体   English

Async / Await - Typescript和ExpressJs

[英]Async/Await - Typescript and ExpressJs

I am experiencing with typescript's async/await in express. 我在express中遇到过typescript的async / await。 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 update2(已修复) - 基于@smnbbrv的答案如下

 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 看起来你的'this'就像你那样传递掉了

router.get('/test', this.test);

If you simply preserve the this value by 如果您只是保留this

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));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM