打字稿:如何在 returns Promise 响应的方法中构建获取 API 调用

Typescript: how to structure a fetch API call inside a method that returns a Promise response

也许是一个微不足道的问题,但我是 Typescript 的新手并获取 API。 在导出的 class 中,我有一个 public 方法 remoteFetchSomething,例如:

export class className {
  remoteFetchSomething = (url : string) : Promise<Response> => {
    return fetch(url)
      .then(
        (r) => r.json()
      )
      .catch((e) => {
        console.log("API errore fetching " + objectType);
      });
  }
}

export const classInstance = new className();

该方法查询远程 JSON API 服务,在代码中,我这样使用它:

import { classInstance } from ...

classInstance.remoteFetchSomething('https://example.url')
  .then((json) => {
    console.log(json);
  }
)

console.log 实际上显示了结果,但是 remoteFetchSomething returns 一个 Promise 我无法解析和访问JSON 个对象值。

我想在执行剩余代码之前等待响应,但如何从 promise 中解包内容?我应该再放一个 .then 吗?我错过了什么?

谢谢。

您不能在 javascript 中等待请求时同步阻塞,它会锁定用户界面!

在常规 javascript 和大多数版本的 TypeScript 中,您应该/必须返回一个承诺。

function doRequestNormal(): Promise<any> {
    return fetch(...).then(...);
}

function someOtherMethodNormal() {
    // do some code here
    doRequestNormal.then(() => {
        // continue your execution here after the request
    });
}

在较新版本的打字稿中,有 async/await 关键字支持 - 所以它可能看起来像这样:

async function doRequestAsync() {
    var result = await fetch(...);
    // do something with request;
    return result;
}

async function someOtherMethodAsync() {
    // do some code here
    var json = await doRequestAsync();
    // continue some code here
}

请记住,doRequestAsync 仍然是 returns 引擎盖下的 Promise - 但是当您调用它时,您可以使用 await 假装您正在阻止它需要使用 .then( 回调。如果您从非异步方法调用异步方法,您仍然需要像往常一样使用回调。

到现在为止,我已经解决了将 remoteFetch 的 return 类型定义为 any:

的问题
remoteFetchSomething = (url : string) : any => {
return fetch(url)
  .then(
    (r) => r.json()
  )
  .catch((e) => {
    console.log("API errore fetching " + objectType);
  });
}

现在我可以访问 JSON 值,例如下面的 data

classInstance.remoteFetchSomething('https://example.url').then(
  (json) => {
    console.dump(json.data);
  }
)

[仍然不清楚为什么我不能使用 Promise<Response> 类型]

我是这样做的:

type Payload = {
    id: number
}

type ReturnType = number

export const functionThatHasNumberType = async (
    payload: Payload
): Promise<ReturnType> => {
    let url = `/api/${payload.id}`

    return await axios.get(url)
}