Typescript - 使用 Fetch 和 Async 访问 Open Trivia Database

Typescript - Using Fetch and Async to access Open Trivia Database

我们正在修改一个使用 TypeScript 和它自己的本地数据库的问答游戏,以改为依赖 Open Trivia DB。有很多我不想弄乱的异步/等待功能(在需要旧数据库功能的情况下),所以我开始使用 Fetch。

到目前为止,这是我的代码:

public async getCategories() {
    let cats = null;
    let counts = null;
    if (!this.IS_USING_OTDB) {
        cats = await this.db.query('SELECT DISTINCT categoryid, category FROM questionsTest ORDER BY categoryid');
        counts = await this.db.query('SELECT categoryid, category, difficulty, count(*) FROM questionsTest GROUP by categoryid, category, difficulty ORDER BY count DESC');
        console.log(cats.rows, cats.rowCount, counts.rows);
    } else {
        console.log('Connecting to opentdb instead of postgres.');
        const fetchResult = await fetch('https://opentdb.com/api_category.php');
        console.log(fetchResult);
        const body = fetchResult.json;
        console.log(JSON.stringify(body));
    }
    // more code for processing here
}

从不会崩溃的意义上说,这本身是可行的。然而,结果(控制台记录 fetchResult)不是我所期望的:

Response {
  size: 0,
  timeout: 0,
  [Symbol(Body internals)]: {
    body: PassThrough {
      _readableState: [ReadableState],
      readable: true,
      _events: [Object: null prototype],
      _eventsCount: 5,
      _maxListeners: undefined,
      _writableState: [WritableState],
      writable: true,
      allowHalfOpen: true,
      _transformState: [Object],
      [Symbol(kCapture)]: false
    },
    disturbed: false,
    error: null
  },
  [Symbol(Response internals)]: {
    url: 'https://opentdb.com/api_category.php',
    status: 200,
    statusText: 'OK',
    headers: Headers { [Symbol(map)]: [Object: null prototype] },
    counter: 0
  }
}

fetchResult.json 的 JSON 压缩结果也是 undefined

这很奇怪,因为 link https://opentdb.com/api_category.php 立即 returns 以下(您可以通过点击上面的 link 自己查看):

{"trivia_categories":[{"id":9,"name":"General Knowledge"},{"id":10,"name":"Entertainment: Books"},{"id":11,"name":"Entertainment: Film"},{"id":12,"name":"Entertainment: Music"},{"id":13,"name":"Entertainment: Musicals & Theatres"},{"id":14,"name":"Entertainment: Television"},{"id":15,"name":"Entertainment: Video Games"},{"id":16,"name":"Entertainment: Board Games"},{"id":17,"name":"Science & Nature"},{"id":18,"name":"Science: Computers"},{"id":19,"name":"Science: Mathematics"},{"id":20,"name":"Mythology"},{"id":21,"name":"Sports"},{"id":22,"name":"Geography"},{"id":23,"name":"History"},{"id":24,"name":"Politics"},{"id":25,"name":"Art"},{"id":26,"name":"Celebrities"},{"id":27,"name":"Animals"},{"id":28,"name":"Vehicles"},{"id":29,"name":"Entertainment: Comics"},{"id":30,"name":"Science: Gadgets"},{"id":31,"name":"Entertainment: Japanese Anime & Manga"},{"id":32,"name":"Entertainment: Cartoon & Animations"}]}

如何从 URL 获取上述结果?我错过了什么吗?

fetchResult.json() 是一种方法,而不是 属性,它 returns 是一个承诺。

The json() method of the Body mixin takes a Response stream and reads it to completion. It returns a promise that resolves with the result of parsing the body text as JSON.

https://developer.mozilla.org/en-US/docs/Web/API/Body/json

试试这个:

const fetchResult = await fetch('https://opentdb.com/api_category.php');
const data = await fetchResult.json();
console.log(data);