gpt4 book ai didi

javascript - 如何在 Promise 中仅返回解析类型?

转载 作者:行者123 更新时间:2023-12-01 15:42:13 25 4
gpt4 key购买 nike

let companyInfo: PublicCompanyAPIResponseType;
companyInfo = await get<PublicCompanyAPIResponseType>({
url: getCompanyDataURL,
}).catch(res => {
responseStatus = res.status;
});

当我将 companyInfo 变量分配给该 get func
export async function get<T>({ url, headers }: ApiConnectSet): Promise<T> {
return new Promise((resolve, reject) => {
fetch(url, {
method: 'GET',
credentials: 'same-origin',
headers: headers,
})
.then(async res => {
if (res.ok) {
return resolve((await res.json()) as Promise<T>);
} else if (res.status === 401) {
const redirectPath = window.location.pathname;
window.location.href =
'/login?redirectPath=' + redirectPath;
} else {
reject(res);
}
})
.catch(error => {
reject(error);
});
});

}

Visual Studio 代码显示此错误
enter image description here

我的 get 函数如何只返回 PublicCompanyAPIResponseType ?

最佳答案

试试这个,如果它有效

let companyInfo: PublicCompanyAPIResponseType;
try {
companyInfo = await get<PublicCompanyAPIResponseType>({
url: getCompanyDataURL,
})
} catch(err => {
// get the status from error object and assign it to response status
responseStatus = // your status code
});

关于javascript - 如何在 Promise 中仅返回解析类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60652016/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com