I want to send an http request and return the result using typescript, before send the http request, I want to get the token from google chrome local storage and put the token into http header. This is my typescript code looks like:
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>;
});
});
},
the problem is the promise return from the inner of an async code block, this function shows error:
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)
what should I do to return the promise inside the chrome local storage get and make the code works?
asyncmethod, and usingawaitstatements instead of callbacks. First GET the token, then prepare the POST using the response from the GET, and then finally return the response from the POST.return fetch(...is inside, and therefore belongs tofunction (result:any) {. Yourapi_postfunction has not return. But the declared return type isPromise<T>