【发布时间】: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