Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript `在Typescript函数中获取`API_Javascript_Typescript_Fetch - Fatal编程技术网

Javascript `在Typescript函数中获取`API

Javascript `在Typescript函数中获取`API,javascript,typescript,fetch,Javascript,Typescript,Fetch,我正在typescript类中使用同构fetch包,并试图确定如何返回FetchAPI响应的值 somefunction(someParam: Int): Int { fetch('myApiURL', { method: 'get'}) .then(function(res) { return res }) .catch(function(ex) { return 0 }) } 您不能返回像Int这样的值,因为JavaScrip

我正在typescript类中使用
同构fetch
包,并试图确定如何返回FetchAPI响应的值

somefunction(someParam: Int): Int {
  fetch('myApiURL', { method: 'get'})
    .then(function(res) {
       return res
    })
    .catch(function(ex) {
       return 0
    })
}
您不能返回像
Int
这样的值,因为JavaScript是单线程的,函数在返回之前不能保留线程。但是,您可以返回一个承诺,这就是
fetch
无论如何返回的内容,因此:

somefunction(someParam: number): Promise<number> {
  return fetch('myApiURL', { method: 'get'})
    .then(function(res) {
       return res
    })
    .catch(function(ex) {
       return 0
    })
}
somefunction(someParam:number):承诺{
返回fetch('myapirl',{method:'get'})
.然后(功能(res){
返回res
})
.catch(函数(ex){
返回0
})
}

PS:这里没有int。只是JavaScript/TypeScript:)中的
number

谢谢basarat。在这种情况下,我如何打开承诺并获得带有
然后
somefunction(123)的value.Chain(val=>{/*use val*/})。更多