`Fetch` API 在 Typescript 函数中

`Fetch` API inside a Typescript function

我在打字稿 class 中使用 isomorphic-fetch 包,并试图确定如何 return 获取 api 响应的值。

somefunction(someParam: Int): Int {
  fetch('myApiURL', { method: 'get'})
    .then(function(res) {
       return res
    })
    .catch(function(ex) {
       return 0
    })
}

你不能 return 像 Int 这样的 因为 JavaScript 是单线程的,函数不能保持线程 人质 直到 returns。但是你可以 return 一个 Promise,这就是 fetch returns 无论如何:

somefunction(someParam: number): Promise<number> {
  return fetch('myApiURL', { method: 'get'})
    .then(function(res) {
       return res
    })
    .catch(function(ex) {
       return 0
    })
}

PS:没有int。在 JavaScript / TypeScript 中只是 number :)