Rjk Rjk - 3 months ago 44
TypeScript Question

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

Answer

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

Comments