【问题标题】:Typescript - Using Fetch and Async to access Open Trivia DatabaseTypescript - 使用 Fetch 和 Async 访问 Open Trivia 数据库
【发布时间】:2020-06-03 08:00:08
【问题描述】:

我们正在修改一个使用 TypeScript 及其自己的本地数据库的问答游戏,改为依赖 Open Trivia DB。有很多我不想弄乱的 async / await 函数(在需要旧数据库功能的情况下),所以我开始使用 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

这很奇怪,因为链接https://opentdb.com/api_category.php立即返回以下内容(您可以通过单击上面的链接自己检查):

{"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 中获取上述结果?我错过了什么吗?

【问题讨论】:

    标签: typescript fetch-api


    【解决方案1】:

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

    Body mixin 的 json() 方法接受一个 Response 流并读取它直到完成。它返回一个 Promise,该 Promise 以将正文文本解析为 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);
    

    【讨论】:

      猜你喜欢
      • 2016-04-01
      • 2020-04-24
      • 2016-06-18
      • 2016-12-08
      • 2013-06-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多