如何将异步方法的结果存储在 class 属性 中?

How to store the result of an async method in a class property?

我正在尝试使用 class 和一个异步方法从网页中获取 HTML。我使用 Typescript 3.4.3,request-promise 4.2.4.

import * as rp from 'request-promise';

class HtmlFetcher {

  public uri: string;
  public html: string;

  public constructor(uri: string) {
    this.uri = uri;
  }

  public async fetch() {
    await rp(this.uri).then((html) => {
      this.html = html;
    }).catch((error) => {
      throw new Error('Unable to fetch the HTML page');
    });
  }

}

export { HtmlFetcher };

我使用以下代码通过 Jest 24.8.0 测试我的 class。第 6 行的地址仅用于测试目的,我也尝试了不同的 URI。

import { HtmlFetcher } from './htmlFetcher.service';

describe('Fetch HTML', () => {

  it('should fetch the HTMl at the given link', () => {
    const uri = 'http://help.websiteos.com/websiteos/example_of_a_simple_html_page.htm';
    const fetcher = new HtmlFetcher(uri);
    fetcher.fetch();

    expect(fetcher.html).toBeDefined();
  });

});

我希望 html 属性 包含调用 fetch() 方法后在给定地址获取的 HTML 字符串。但是,测试代码失败,并记录 fetcher.htmlundefined。 Typescript、Jest 和 request-promise 文档没有提供任何帮助。我做错了什么?

感谢 TKoL's comments, and another look at a doc I already read 50 times, namely: Jest async testing 找到了答案。我应该更仔细地使用 RTFM...

测试代码也必须是异步的。

import { HtmlFetcher } from './htmlFetcher.service';

describe('Fetch HTML', () => {

  it('should fetch the HTMl at the given link', async () => { // Added async keyword
    const uri = 'http://help.websiteos.com/websiteos/example_of_a_simple_html_page.htm';
    const fetcher = new HtmlFetcher(uri);
    await fetcher.fetch(); // Added await keyword

    expect(fetcher.html).toBeDefined();
  });

});