我想发送一个http请求,并使用typescript返回结果,在发送http请求之前,我想从谷歌chrome本地存储中获取令牌,并将令牌放入http头中。这是我的打字代码看起来像:
api_post:<T>(url: string, data: any): Promise<T> => {
chrome.storage.local.get("token", function (result:any) {
return fetch(url, {
method: 'POST',
headers: {
'Content-type': 'application/json',
'x-access-token': result,
},
body: JSON.stringify(data),
})
.then(response => {
if (!response.ok) {
throw new Error(response.statusText);
}
return response.json() as Promise<T>;
});
});
},
问题是来自异步代码块内部的promise返回,此函数显示错误:
interface Promise<T>
Represents the completion of an asynchronous operation
A function whose declared type is neither 'void' nor 'any' must return a value.ts(2355)
我应该怎么做才能在chrome本地存储get中返回promise并使代码正常工作?
我会使用Promise构造函数。然后,解析链中的最终所需值,并拒绝任何错误。
const api_post = <T>(url: string, data: any): Promise<T> => {
return new Promise((resolve, reject) => {
chrome.storage.local.get("token", function (result: any) {
return fetch(url, {
method: "POST",
headers: {
"Content-type": "application/json",
"x-access-token": result,
},
body: JSON.stringify(data),
}).then((response) => {
if (!response.ok) {
reject(new Error(response.statusText));
return;
}
resolve(response.json() as Promise<T>);
});
});
});
};
要跟进我的评论,您可以执行以下操作:
api_post: async (url: string, data: any): Promise<T> => {
const { result } = await chrome.storage.local.get("token");
const response = await fetch(url, {
method: 'POST',
headers: {
'Content-type': 'application/json',
'x-access-token': result,
},
body: JSON.stringify(data),
});
return response;
},
注意:这只是为了让您了解如何使用async
/await
重构方法。这个代码可能需要一些调整。
只是插入了另一个片段,因为OP似乎不喜欢Ross Gatih的答案中的async/await
,而我不喜欢Jordan Wrights的新Promise反模式答案
const api_post = <T>(url: string, data: any): Promise<T> => {
return chrome.storage.local.get("token")
.then((result: any) => fetch(url, {
method: "POST",
headers: {
"Content-type": "application/json",
"x-access-token": result,
},
body: JSON.stringify(data),
}))
.then((response) => {
if (!response.ok) {
throw new Error(response.statusText);
}
return response.json();
});
};