[英]Return type for asynchronous function
I have this code that is a simple implementation of async/await while doing ajax call我有这段代码,它是 async/await 在进行 ajax 调用时的简单实现
export const getExternalResource = async (): Promise|String|null => {
return new Promise(async (resolve, reject) =>{
const response = await fetch(url);
const json = response.json();
if(json) {
resolve(json);
} else {
resolve(null)
}
});
};
/**
* @var resource will be null|string
*/
const resource = await getExternalResource();
My question is what is the correct return type for the getExternalResource()
function?我的问题是
getExternalResource()
function 的正确返回类型是什么?
In code it returns a promise, however when calling the function with await
keyword, it returns a basic data type (string|null).在代码中它返回一个 promise,但是当使用
await
关键字调用 function 时,它返回一个基本数据类型 (string|null)。
You dont need a fetch
inside a Promise
since fetch
returns a promise. Also return type of an async function or method must be the global Promise type.您不需要在
Promise
中进行fetch
,因为fetch
返回 promise。此外,异步 function 的返回类型或方法必须是全局 Promise 类型。 So changed the return type here to Promise<any>
.所以将此处的返回类型更改为
Promise<any>
。 You can replace any
with the matching type您可以用匹配的类型替换
any
export const getExternalResource = async(url: string): Promise<any> => {
return await fetch(url).then(response => response.json());
};
const resource = getExternalResource('url').then(d=>d);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.