【问题标题】:Typescript: how to structure a fetch API call inside a method that returns a Promise responseTypescript:如何在返回 Promise 响应的方法中构造 fetch API 调用
【发布时间】:2017-07-30 04:58:51
【问题描述】:

也许一个微不足道的,但我是 Typescript 和 fetch API 的新手。 在导出的类中,我有一个公共方法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 返回一个 Promise,我无法解析和访问 JSON 对象值。

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

谢谢。

【问题讨论】:

    标签: javascript typescript promise fetch


    【解决方案1】:

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

    在较新版本的 typescript 中,支持 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 仍然会在后台返回一个 Promise - 但是当您调用它时,您可以使用 await 假装您正在阻止它,而不是需要使用 .then( 回调。如果您从非异步方法调用异步方法,您仍然需要照常使用回调。

    【讨论】:

    • 抱歉,可能是我的问题不清楚:问题不在于 Promise 链接和等待,而是关于 remoteFetchSomething 方法的返回类型:作为 Response&lt;Promise&gt; 我无法解析另一边的json。如果我将方法返回类型定义为any 它可以工作。
    【解决方案2】:

    现在我解决了将remoteFetch 的返回类型定义为any 的问题:

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

    现在我可以访问下面的 data 之类的 JSON 值:

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

    [真诚地仍然不清楚为什么我不能'使用Promise&lt;Response&gt;类型]

    【讨论】:

    【解决方案3】:

    这就是我的做法:

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

    【讨论】:

      猜你喜欢
      • 2019-12-19
      • 1970-01-01
      • 2017-09-13
      • 1970-01-01
      • 1970-01-01
      • 2017-09-05
      • 2017-12-05
      • 2020-07-18
      • 1970-01-01
      相关资源
      最近更新 更多