Rjk
Rjk

Reputation: 1474

`Fetch` API inside a Typescript function

I am using isomorphic-fetch package inside a typescript class and trying to identify how I can return the value of the fetch api response.

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

Upvotes: 1

Views: 7002

Answers (1)

basarat
basarat

Reputation: 276239

You can't return a value like Int because JavaScript is single threaded and the function cannot hold the thread hostage till it returns. However you can return a Promise, that is what fetch returns anyways so:

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

PS: there is no int. Just number in JavaScript / TypeScript :)

Upvotes: 2

Related Questions