1

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

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

2 Comments

thanks basarat. In that case how can I unwrap the promise and get the value.
Chain with a then somefunction(123).then(val=>{/*use val*/});. More basarat.gitbooks.io/typescript/content/docs/promise.html

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.